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 thetoString()
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 toA
, an int field and a float field. Composition
class has a constructor using its fields and also overrides thetoString()
API method of Object.- We create a new instance of
Composition
and call itstoString()
method to print it. - Its constructor is called where
A
constructor is also called to initializeA
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.