一个类怎么会有自己类型的成员,这不是无限递归吗? [英] How can a class have a member of its own type, isn't this infinite recursion?

查看:29
本文介绍了一个类怎么会有自己类型的成员,这不是无限递归吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了一个类,该类的成员是一个与自身类型相同的变量.

Say I define a class that has as a member a variable of the same type as itself.

public class Abc {
    private Abc p;
}

这确实有效,令我惊讶.

This actually works, much to my surprise.

为什么我认为不应该:创建一个 Abc 的实例,它包含一个 Abc 类型的变量,其中包含一个 Abc<类型的变量/code>,它包含一个 Abc 类型的变量,它 .....

Why I think it shouldn't: creating an instance of Abc, it contains a variable of type Abc, which contains a variable of type Abc, which contains a variable of type Abc, which .....

显然我错了,有人可以启发我吗?

Obviously I'm wrong, could someone enlighten me as to how?

推荐答案

您只是声明变量而不是创建变量.尝试在声明或构造函数中创建它,让我知道会发生什么:

You're only declaring the variable and not creating it. Try creating it at declaration or in the constructor and let me know what happens:

public class Abc {
   private Abc p = new Abc(); // have fun!

   public static void main(String[] args) {
      new Abc();
   }
}

顺便说一句,如果您不在类中创建它,而是在 getter 方法或构造函数参数中接受对它的引用,则您的代码将正常工作.这就是一些链表的工作原理.

Incidentally, if you don't create it in the class, but rather accept a reference to it in a getter method or a constructor parameter, your code will work just fine. This is how some linked lists work.

这篇关于一个类怎么会有自己类型的成员,这不是无限递归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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