Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instance of a class inside that class in java

Tags:

java

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();
    }
}
like image 458
Sachin Sabbarwal Avatar asked Dec 22 '22 06:12

Sachin Sabbarwal


1 Answers

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.

like image 176
Brian Roach Avatar answered Jan 11 '23 00:01

Brian Roach