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 ?
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...
}
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.
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;
}