Instance of a class inside this class in java

Here I declare an instance of an animal class in the same class. B c Considered an error:

struct demo{ int anyvar; struct demo anyvar1; }; 

since it should be an infinite ad loop.

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(); } } 
+4
source share
1 answer

Since in Java you declare a variable that contains a reference value; pointer.

I like to do this:

 struct demo{ int anyvar; struct demo *anyvar1; }; 

All objects in java are created on the heap, and they are explicitly created using the new keyword.

 public class Node { Node next; String value; public Node() { ... } ... } 

next and value automatically initialized to null when the Node object is created and remains so until it is assigned a reference value.

+11
source

Source: https://habr.com/ru/post/1379805/


All Articles