简体   繁体   English

在超类构造函数中创建子类对象进入无限循环java

[英]creating subclass object in superclass constructor goes in infinite loop java

This might be a silly question, but please bear with me for now. 这可能是一个愚蠢的问题,但请现在请耐心等待。 I have something similar to: 我有类似的东西:

     public class A{


    public A(){
        //Some statements here

        B bObj = new B(); //Goes in infinite loop this above statement

        (new Thread(bObj)).start();
        //Some statements here


    }

    public static void main(String[] args){
         A aObj = new A();

        }

    }
}

class B extends A implements Runnable{
    public testprint(){
        System.out.println("Inside testprint()");
    }
}

If I create a subclass object in the superclass, it goes in infinite loop, because I guess once subclass object is created it keeps calling superclass constructor which keeps creating subclass object. 如果我在超类中创建一个子类对象,它会进入无限循环,因为我想一旦创建了子类对象,它就会一直调用超类构造函数,它继续创建子类对象。 If I declare the subclass object in main, I get something like 'Cannot reference non-static member from static context' because my superclass object is not yet initialized. 如果我在main中声明子类对象,我会得到类似'无法从静态上下文引用非静态成员'的内容,因为我的超类对象尚未初始化。 So I cannot initialize my subclass object in main. 所以我无法在main中初始化我的子类对象。

So what would be a good way to deal with this? 那么处理这个问题的好方法是什么?

A couple things I see going on that's wrong. 我看到的一些事情是错的。 First, as per the comments, you can't create an instance of B in the constructor of B's parent class. 首先,根据注释,您不能在B的父类的构造函数中创建B的实例。 That would be an infinite loop. 这将是一个无限循环。

Also, I see you call "new bObj". 另外,我看到你称之为“新bObj”。 You meant new B() I assume? 你的意思是新B()?

You want to create an instance of B instead of A, then in B's constructor, when starting the thread, you'd want to pass "this" to the Thread object, rather than trying to create a new instance. 你想创建一个B而不是A的实例,然后在B的构造函数中,当启动线程时,你想要将“this”传递给Thread对象,而不是试图创建一个新实例。

And lastly, you really shouldn't try starting the thread in the constructor anyway. 最后,你真的不应该尝试在构造函数中启动线程。 You'd effectively be passing, to the Thread class, an object that's not fully constructed yet. 你有效地将一个尚未完全构造的对象传递给Thread类。 Should start it after the object is constructed. 应该在构造对象后启动它。

Don't forget that every B is an A . 不要忘记每个B都是A So every time you try to create a B , you are in fact creating an A . 因此,每次尝试创建B ,您实际上都在创建A

Now look at your code again. 现在再看一下你的代码。 In your constructor for A , which of course gets called every time you create an A , you've said "start by creating an A ". A的构造函数中,当然每次创建A时都会调用它,你说“从创建A开始”。 Were you not expecting an infinite loop? 你不期待无限循环吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM