Class Test {
Test variable1 = null;
Test variable2 = new Test();
}
Run Code Online (Sandbox Code Playgroud)
我们可以对两个变量执行类似的功能吗?
在同一个类中创建一个类的引用变量是否正确?
是的,这是正确的
通过一个示例,您将了解更多信息,请考虑您有一个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)
如您所见,您可以根据需要使用构造函数。