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 ?
That would depend entirely on the class.
Like any other instance member.
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:
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):
prev
,next
,parent
,child
,firstChild
,lastChild
,prevSibling
,nextSibling
, ... .It is very common to have fields of the same type as the class in order to implement data structures like linked lists, trees etc in java.
It is basically the same as what pointers are used for this purpose in C.
As every object that is created in java is actually a "reference" to the actual location of object in heap, hence in a way you can view them as pointers would be in C.
so something like:
struct List{ int val; List *next; }
would be in java be like:
class MyList{ int val; MyList nextNode; }
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.