在类中具有相同类的字段

ton*_*099 1 java field class

请考虑以下示例

public class Human
{
public Human h1;
public String name;
public int age;

public Human()
{
  name = "myName";
      age = 22;
}
}
Run Code Online (Sandbox Code Playgroud)

在那里有一个h1有什么意义?它怎么用?为什么会被使用?我们不能只使用我们用新创建的实例吗?

T.J*_*der 5

在那里有一个h1有什么意义?

这完全取决于课程.

它怎么用?

像任何其他实例成员一样.

为什么会被使用?我们不能只使用我们用新创建的实例吗?

考虑一个链表,其中每个节点都有指向下一个(可能是前一个)节点的链接.这些链接与节点本身是同一个类.例如,大致:

class LinkedListNode {
    private LinkedListNode previous;
    private LinkedListNode next;
    private Object value;

    LinkedListNode(LinkedListNode p, LinkedListNode n, Object v) {
        this.previous = p;
        this.next = n;
        this.value = v;
    }

    LinkedListNode getPrevious() {
        return this.previous;
    }

    // ...and so on...
}
Run Code Online (Sandbox Code Playgroud)

还有很多其他类似的用例.一个Person班级可能有相关人员(配偶,子女).树类可能会有叶子,可能会有其他叶子的链接.等等.


在评论中,您询问了一个单例类.是的,这绝对是一个你有一个类的成员的情况.这是一个标准的单身人士(这个主题有很多变化):

class Foo {
    // The singleton instance
    static Foo theInstance = null;

    // Private constructor
    private Foo() {
    }

    // Public accessor for the one instance
    public static synchronized Foo getInstance() {
        if (theInstance == null) {
            theInstance = new Foo();
        }
        return theInstance;
    }

    // ...stuff for Foo to do, usually instance methods...
}
Run Code Online (Sandbox Code Playgroud)