Create a subclass object when the parent class is initialized

advertisements

is there a way to automatically initialize a subclass when the parent-class is initialized(constructed)?

For example like this:

public class Parent {
    public Parent() { //Constructor
    ...
    }

    public class Child {
        public void foo() {
        ...
        }
    }
}

I want to be able to do something like this:

Parent p = new Parent();
p.Child.foo();

Any Ideas? I think it's all about static-ness but I'm not sure, so any help is appreciated. Thanks in advance.


You cannot call it that way.

If the child class must be a non-static class and reside inside a parent class then you will have to initiate it either in the parent class or outside of it before using any of its methods.

You have this option.

public class Parent {

    private Child child;

    public Child getChild() {
        return child;
    }

    public Parent() { //Constructor
        this.child = new Child();
    }

    public class Child {
        public void foo() {
            ...
        }
    }
}

After that you can call the foo() method this way.

Parent p = new Parent();
p.getChild().foo();