【发布时间】:2018-11-19 20:47:28
【问题描述】:
我是 Java 编程的初学者。我不明白这段代码的作用。在 cat 类中,我不了解变量 Cat parent。它将保持什么价值?
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String motherName = reader.readLine();
Cat catMother = new Cat(motherName);
String daughterName = reader.readLine();
Cat catDaughter = new Cat(daughterName, catMother);
System.out.println(catMother);
System.out.println(catDaughter);
}
public static class Cat {
private String name;
private Cat parent;
Cat(String name) {
this.name = name;
}
Cat(String name, Cat parent) {
this.name = name;
this.parent = parent;
}
@Override
public String toString() {
if (parent == null)
return "The cat's name is " + name + ", no mother ";
else
return "The cat's name is " + name + ", " + parent.name + " is the mother";
}
}
当我看到 Cat 父级在 Cat 类中声明为变量时,我感到很困惑!
【问题讨论】:
-
父母也是猫。
-
一个
Cat有一个父级,这个父级也是一个Cat。在您的代码中,parent字段将包含对当前Cats 父级的引用(如果未提供父级,则为null) -
您可以拥有自己类型的类变量。从逻辑上讲,猫的父母也是猫。 Java 中没有任何东西可以阻止您这样做,事实上,一旦您学习了更复杂的数据结构,它就会非常有用。