mrybak3
mrybak3

Reputation: 425

Calling a subclass constructor from a superclass

I am first encountering inheritance in java and I have an issue with constructors.

Consider class A

class A{
    ...(Constructor) {
        ...
        ObjectCreatedBySubClass= new B();
        }
    ...(etc)


    protected static B    ObjectCreatedBySubClass;    
}

Along with its subclass

class B extends A{
    B(){
    ..(No matter what code I put here, it does not work.)
    }


    ...(Instance variables)
}

No matter what I change, every time I get

Exception in thread "main" java.lang.StackOverflowError
at A.<init>
at B.<init>
(repeat about 100 times)

My professor explained that I should not be "extending" a "has-a" relationship, as is the case here. I am going to use composition instead of inheritance to solve my issue, but my question is

I don't understand why the issue is occurring. It is running out of memory because of (I assume) some sort of infinite looping, but I don't know why. How would I properly use inheritance in this case?

Any help would be greatly appreciated.

Upvotes: 0

Views: 583

Answers (2)

SomeDude
SomeDude

Reputation: 14238

This is because when you construct A which you are constructing B inside, when the constructors of subclass are called, the constructors of super class are also called. So it is going in an infinite loop.

Upvotes: 1

wX2qJ2hUdVhnMtWE
wX2qJ2hUdVhnMtWE

Reputation: 46

Since B extends A, every time you call B's constructor, you will also call A's. However, in your implementation of A's constructor, you instantiate a B which, on it's construction, calls A's constructor. This circular dependency is never broken which leads to your stack overflowing.

Upvotes: 1

Related Questions