在一个班级中有一个具有相同班级的字段 [英] having a field with the same class inside a class
问题描述
考虑以下示例
public class Human
{
public Human h1;
public String name;
public int age;
public Human()
{
name = "myName";
age = 22;
}
}
在其中拥有h1有什么意义?如何使用?以及为什么要使用它?
我们不能只使用将用新的实例创建的实例吗?
What is the point of having a h1 in there ? How can it be used ? and why would it be used ? Can't we just use the instance that we would create with the new ?
推荐答案
在其中有h1的意义是什么?
What is the point of having a h1 in there ?
这完全取决于类。
如何使用?
How can it be used ?
像其他任何实例成员一样
Like any other instance member.
为什么要使用它?我们不能只使用将用新的实例创建的实例吗?
and why would it be used ? Can't we just use the instance that we would create with the new ?
考虑一个链表,其中每个节点都有链接下一个(可能是上一个)节点。这些链接与节点本身属于同一类。例如,大致:
Consider a linked list, where each node has links to the next (and possibly previous) nodes. Those links would be the same class as the node itself. E.g., roughly:
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...
}
还有许多其他类似的用例。 人
班级可能有关联人员(配偶,孩子)的成员。一个树类可能有叶子,而叶子可能有到其他叶子的链接。等等。
There are lots of other similar use cases. A Person
class might have members for associated persons (spouses, children). A tree class probably would have leaves, which would probably have links to other leaves. Etc.
在评论中,您询问了单例课程。是的,绝对是在这种情况下,您会有一个属于此类的成员。这是一个标准的单例(此主题有很多变体):
In the comments, you asked about a singleton class. Yes, that's absolutely a case where you'd have a member that was the type of the class. Here's a standard singleton (there are many variations on this theme):
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...
}
这篇关于在一个班级中有一个具有相同班级的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!