Java:继承self的类 [英] Java : Class inheriting self

查看:108
本文介绍了Java:继承self的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是毫无意义的:我发现它很有趣,我想更多地询问当你创建一个继承自身的类时会发生什么的机制,导致堆栈溢出崩溃。令人惊讶的是,Java允许你开始构建这样的构造。

I know this is pointless: I just find it funny and I want to inquire more about the mechanics of what happens when you create a class that inherits itself, resulting in a stack overflow crash. It's amazing that Java allows you to make such a construct to begin with.

我只是猜测,但是JVM将自己置于一个无限循环中试图解决这个问题在实例化之前,还是实际上无休止地实现课程的多个副本?

I am just guessing, but is the JVM putting itself into an infinite loop trying to resolve the class before instancing it, or is it actually instancing multiple copies of the class endlessly?

我本来应该更具体;我使用内部类来从封闭类派生。

I should have been more specific; I am using an inner class to derive from enclosing class.

 public class Outside {
    private int outsideValue;

    public class Inside extends Outside {
        private int insideValue;
        public Inside(int val) {
            insideValue = val;
        }
    }

    public Outside() {
        Inside o = new Inside(0);
    }
}

public class Main {
    public static void main(String args[]) {
        Outside o = new Outside();
    }
}


推荐答案

记住因为内部扩展外部,它有一个隐式调用 super( ) 这是 Outside 的构造函数(后者又调用的构造函数)所以它会四处走动。

Remember that, since Inside extends Outside, it has an implicit call to super() which is the constructor of Outside (which in turn calls the constructor of Inside) and so it goes around.

您发布的代码在概念上与以下程序没有区别

class A {
    B b = new B();
}

class B extends A {
}

public class Test {
    public static void main(String[] args) {
        new A(); // Create an A...
                 //   ... which creates a B
                 //   ... which extends A thus implicitly creates an A
                 //   ... which creates a B
                 //   ...
    }
}

这篇关于Java:继承self的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆