class

Initialize constructor with composition

This is an example of how to initialize a constructor with composition. We have created an object with reference to another object, as described below:

  • We have created class A that has a String field and overrides the toString() API method of Object, where it returns its String field.
  • We have also created a class, Composition that has four String fields, a field that is reference to A, an int field and a float field.
  • Composition class has a constructor using its fields and also overrides the toString() API method of Object.
  • We create a new instance of Composition and call its toString() method to print it.
  • Its constructor is called where A constructor is also called to initialize A field.
  • Then its toString() method is called, that returns all values of Composition’s fields.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;


class A {

    private String s;

    A() {

  System.out.println("A()");

  s = "Constructed";
    }

    @Override
    public String toString() {

  return s;
    }
}

public class Composition {

    private String string1 = "Happy", string2 = "Happy", string3, string4;
    private A obj;
    private int i;
    private float toy;

    public static void main(String[] args) {

  Composition b = new Composition();

  System.out.println(b);

    }

    public Composition() {

  System.out.println("Inside A()");

  string3 = "Joy";

  i = 47;

  toy = 3.14f;

  obj = new A();
    }

    @Override
    public String toString() {

  if (string4 == null) // Delayed initialization:

  {


string4 = "Joy";

  }

  return "s1 = " + string1 + "n" + "s2 = " + string2 + "n" + "s3 = " + string3 + "n"


    + "s4 = " + string4 + "n" + "i = " + i + "n" + "toy = " + toy


    + "n" + "castille = " + obj;
    }
}

Output:

Inside A()
A()
s1 = Happy
s2 = Happy
s3 = Joy
s4 = Joy
i = 47
toy = 3.14
castille = Constructed

  
This was an example of how to initialize a constructor with composition in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button