一个类是否可以拥有自己类型的字段 [英] Is it okay for a class to have a field of its own type

查看:175
本文介绍了一个类是否可以拥有自己类型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了以下操作,一段时间后我遇到了stackoverflow错误,我明白为什么会这样。

I did the following, i got a stackoverflow error after some time, and I understand why it was.

public class Cat {
    String name="default name";
    Cat insideCat;

    public Cat(){
         System.out.println("Cat constructor");
         insideCat = new Cat();
    }

}

但如果我不这样做怎么办?在构造函数中创建一个新的Cat对象,但是获取Cat类型的参数并将其分配给insideCat字段。

But what if I don't create a new Cat object within the constructor, but take a parameter of Cat type and assign it to the insideCat field.

public class Cat {
    String name="default name";
    Cat insideCat;

    public Cat(Cat insideCat){
         System.out.println("Cat constructor");
         this.insideCat = insideCat;
    }

}

我只是玩弄代码,只是试图找出Java可以做什么,不能做什么。在第二个代码中,一切看起来都很正常,直到我开始测试这个类。我需要一个Cat对象来创建一个Cat对象(并创建这个Cat对象,我需要另一个Cat对象......然后它继续)。所以从技术上讲,我无法测试这门课程。

I am just playing around with the code, just trying to find out what Java can do and cannot. In the second code, everything looked normal, until I started to test this class. I need a Cat object to create a Cat object (and to create this Cat object I need another Cat object...and it goes on). So technically I cannot test this class.

所以我的问题是为什么java允许创建自己类型的实例变量?我想构造函数的整个目的是初始化它的实例变量。所以要么我必须创建一个新对象来初始化insideCat,否则我必须从外面获取Cat对象。两者似乎都不起作用。

So my question is WHY does java allow to create an instance variable of its own type? I guess the whole purpose of a constructor is to initialize it's instance variables. So either I have to create a new object to initialize the insideCat or else I have to take Cat object from outside. Both doesn't seem to work.

我在这里缺少什么。是否存在其自身类型的实例变量可以变得有用的情况,并且可以毫无问题地使用?提出像这样的课程是不是很糟糕的OOP练习?

What am I missing here. Is there any occurrence where instance variables of its own types can become useful, and can be used without any problem? Is it bad OOP practice to come up with classes like this?

推荐答案

这类课程一直存在。

考虑关联列表或树,例如,

Consider linked lists or trees, e.g.,

class ListNode {
  ListNode next;
  // Etc.
}

class TreeNode {
  TreeNode left;
  TreeNode right;
  // Etc.
}

你不会初始化孩子 构造函数中的对象,您稍后会添加它们。

You wouldn't initialize the "child" objects in the constructor, you'd add them later.

在您的示例中,您需要一个创建 insideCat <的方法/ code>稍后。一般情况下,你不会创建具有完全相同状态的子对象,在构造时可以区分它们,在这种情况下你可以有一个哦,上帝停止创建这些现在的条件,或者它们是被添加,例如,你通过一个方法而不是在构造函数中添加它们。

In your example you'd need to have a method that created the insideCat at a later time. In general you wouldn't create child objects that had the exact same state, there'd be something to differentiate them either at construction time, in which case you could have a "oh god stop creating these now" condition, or while they were being added, e.g., you'd add them via a method and not in a constructor.

这篇关于一个类是否可以拥有自己类型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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