TheLexoPlexx
TheLexoPlexx

Reputation: 117

Create Sub-Class Object when Parent Class is initialized

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.

Upvotes: 1

Views: 121

Answers (3)

Alberto Ruiz Bueno
Alberto Ruiz Bueno

Reputation: 116

Try this code:

This first part is the main. You have to invoke que Parent and make an instance the Child (That is the first lane of the code) After that, you can use the child methods.

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

On the other hand, the class:

    public class Parent {

public Parent(){

}

protected void foo(){

}

public class Child extends Parent{
    public Child(){

    }

    @Override
    public void foo(){
        System.out.println("I am the child!!");
    }
}

}

As you can see that is very similar that you have, but you have to write in the child "extends Parent" to specify the parent of that class.

I hope that could help you!!!

Upvotes: 0

user1326628
user1326628

Reputation:

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();

Upvotes: 2

StephaneM
StephaneM

Reputation: 4899

Maybe somehting like that:

public class Parent {
    public Parent() { //Constructor
      foo();
    }

    protected void foo() {
    // Do nothing in parent
    }
}

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

Edit: this is not a correct anwser as Child does not extend Parent.

Upvotes: 0

Related Questions