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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With