简体   繁体   English

java中该类内部类的实例

[英]instance of a class inside that class in java

Here i'm declaring an instance of class animal in the same class. 在这里,我宣布同一类中的类动物实例。 In c It is considered an error: 在c中它被认为是一个错误:

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? 然后,为什么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 ; 因为在Java中你声明一个包含引用值的变量; 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. java中的所有对象都是在堆上创建的,并且使用new关键字显式创建它们。

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. nextvalue在实例化Node对象时自动初始化为null ,并且将保持为null ,直到为它们分配引用值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM