Here i'm declaring an instance of class animal in the same class. In c It is considered an error:
struct demo{
int anyvar;
struct demo anyvar1;
};
because it is supposed to be an infinite loop of declaration.
Then, Why is this code allowed in Java?
class Animal{
Animal object1 = new Animal();
public static void main(String[] args)
{
Animal obj = new Animal();
obj.dostuff();
}
public void dostuff()
{
System.out.println("Compiles");
object1.dostuff();
}
public void keepdoingstuff()
{
System.out.println("Doing Stuff...");
object1.keepdoingstuff();
}
}
Because in Java you're declaring a variable that contains a reference value; a pointer.
It's like doing:
struct demo{
int anyvar;
struct demo *anyvar1;
};
All objects in java are created on the heap, and they are explicitly created with the new
keyword.
public class Node
{
Node next;
String value;
public Node() { ... }
...
}
next
and value
are automatically initialized to null
when a Node
object is instantiated and will remain so until a reference value is assigned to them.
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