在同一个类中创建一个类的引用变量是否正确?与使用new关键字创建普通对象有何不同?

Kni*_*ale 1 java class

Class Test {
   Test variable1 = null;
   Test variable2 = new Test();
}
Run Code Online (Sandbox Code Playgroud)

我们可以对两个变量执行类似的功能吗?

YCF*_*F_L 5

在同一个类中创建一个类的引用变量是否正确?

是的,这是正确的

通过一个示例,您将了解更多信息,请考虑您有一个Person类:

class Person {

    String name;
    int age;

    Person mother;
    Person father;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name, int age, Person mother, Person father) {
        this.name = name;
        this.age = age;
        this.mother = mother;
        this.father = father;
    }

}
Run Code Online (Sandbox Code Playgroud)

每个人都是有父母的人,而父母是人。

例如,您:

Person p1 = new Person("Son Name", 22, 
       new Person("Mother name"), 45), new Person("Father name"), 50));
Run Code Online (Sandbox Code Playgroud)

或者您可以这样创建它:

Person mother = new Person("Mother name", 45);
Person father = new Person("Father name", 50);
Person son =    new Person("Son name", 22, mother, father);
Run Code Online (Sandbox Code Playgroud)

如您所见,您可以根据需要使用构造函数。

  • @Aganju这里的“参考变量”一词不正确。您的意思是实例变量。如果直接将实例直接分配给实例,而实例又导致创建相同类或子类的对象,则只会导致无限递归。如果将要分配给变量的对象传递给构造函数或在构造后分配,这不是问题。 (2认同)
  • @Aganju这是Java。这里没有明确的指针。没有创建“默认”实例来分配给这些实例变量,默认情况下它们被初始化为“ null”。 (2认同)