1

I have 2 classes:

public abstract class Parent {
    private AnyObject anyObject = createObject();

    public abstract AnyObject createObject();
}

public class Child extends Parent {
    public Child() {
        System.out.println("Constructing child...");
    }

    @Override
    public AnyObject createObject() {
        System.out.println("Creating object...");
        return new AnyObject();
    }
}

Constructing child

Child c = new Child();

prints the following lines:

Creating object...
Constructing child...

An object must be constructed before a method can be called upon that. I know that a parent must be constructed before a child and mine is a very unusual example. I need to set a few fields in constructor which will be used in createObject().

Shahzad
  • 508
  • 7
  • 16

0 Answers0