Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

having a field with the same class inside a class

Tags:

java

class

field

Consider this following example

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

public Human()
{
  name = "myName";
      age = 22;
}
}

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 ?

like image 670
tony9099 Avatar asked Mar 24 '26 12:03

tony9099


2 Answers

What is the point of having a h1 in there ?

That would depend entirely on the class.

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...
}
like image 98
T.J. Crowder Avatar answered Mar 26 '26 08:03

T.J. Crowder


One of the example, If you have a tree like structure then a node can contain child of its own type. That is the reason your Human class has an attribute of its own type.

like image 28
Juned Ahsan Avatar answered Mar 26 '26 09:03

Juned Ahsan