mahela007
mahela007

Reputation: 1439

Sub class instance variable in super-class object?

Let's say I have two classes called "SuperClass" and SubClass. SubClass extends SuperClass.

I just found out that it's not possible for SuperClass to have an instance variable of type SubClass.

That is, this will not work:

class SuperClass{
     SubClass x = new SubClass();
}

because it causes the constructors to call each other, entering a perpetual loop. (because Java automatically puts in the call to Super())

Is creating a subclass instance variable impossible and a bad design idea? or is there some kind of work-around?

Upvotes: 1

Views: 161

Answers (2)

Hot Licks
Hot Licks

Reputation: 47729

The only restriction is in placing an allocation of the subclass (or, for that matter, another instance of the superclass) within the superclass constructor. You can most certainly have an instance field with the type of a subclass, and set it at some point after construction of the superclass. (Though you would obviously need to prevent any recursion via the setter method.)

And actually one could put the allocation in the superclass constructor if there were conditional logic in the constructor to skip the allocation if constructing the subclass. Eg:

class SuperClass {
    SubClass subClassField;
    SuperClass() {
        if (!(this instanceof SubClass)) {
            subClassField = new SubClass();
        }
    }
}

But, of course, just because you can do this does not say that you should. While I can imagine a few scenarios where it might be a valid approach, they would be "oddball" situations.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425003

It is generally a bad idea. If your super class needs an instance of a subclass, that's a code smell. It creates circular dependencies and suggests a broken analysis.

The workaround/fix is usually to bring up whatever code the super class is using from the subclass into the super class.

Upvotes: 2

Related Questions