本文介绍了从超类调用子类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次在Java中遇到继承问题,而构造函数也有问题.

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

考虑A类

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


    protected static B    ObjectCreatedBySubClass;
}

及其子类

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.

推荐答案

由于B扩展了A,因此每次调用B的构造函数时,您也将调用A的构造函数.但是,在实现A的构造函数的过程中,您实例化了一个B,在构造B时,它调用了A的构造函数.这种循环依赖性永远不会中断,从而导致您的堆栈溢出.

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.

这篇关于从超类调用子类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:18
查看更多