Calling a subclass constructor from a superclass

浪子不回头ぞ 提交于 2019-12-12 02:44:55

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/35109358/calling-a-subclass-constructor-from-a-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!