【问题标题】:Why does the Cat class use Cat parent as instance variable?为什么 Cat 类使用 Cat 父级作为实例变量?
【发布时间】: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 中没有任何东西可以阻止您这样做,事实上,一旦您学习了更复杂的数据结构,它就会非常有用。

标签: java swing class


【解决方案1】:

看看你的 main 方法中的行...

这一行创建了一个新的Cat,其名称(之前由输入定义):

Cat catMother = new Cat(motherName);

虽然以下行也创建了一个新的Cat,但使用了不同的构造函数(具有两个参数的构造函数):

Cat catDaughter = new Cat(daughterName, catMother);

如果您只是阅读参数的名称,您可以清楚地看到关系...使用此构造函数为新的Cat 提供了一个名字(女儿)和一个亲戚(母亲)。这个亲戚作为属性存储在Cat 类中。所以Cat 的每个实例都有另一个Cat 作为父级或null(后者可能会导致一些不同的问题)。

然后看看Cat的类属性,这是设置(或不设置)值的地方:

private String name; // this is where the name of the cat object is stored
private Cat parent;  // this is where mother or father is stored (yes, only one possible at a time)

在 Java 中,某个类的实例具有同一类的另一个实例作为属性是很常见的,这与 String 类的对象没有什么不同,只是另一种类型的对象。

【讨论】:

    【解决方案2】:

    Cat parent 是分配给另一个 Cat 对象的 Cat 对象。

    这里创建了 Cat 父级:

    String motherName = reader.readLine();
    Cat catMother = new Cat(motherName);
    

    在这里它被分配给另一个猫对象“catDaughter”

    String daughterName = reader.readLine();
    Cat catDaughter = new Cat(daughterName, catMother);
    

    换句话说,使用父字段,您可以在几个 Cat 对象之间创建关系。

    【讨论】:

    • 好吧我明白了,当输入motherName时,它被传递给变量名,当输入daughterName时,它仍然被传递给name,但现在motherName被传递给父名,就是这样我明白了吗??
    • Cat Parent 和 Cat Child 对象的区别在于使用的构造函数。如果你使用 Cat(String name) - 这只猫没有孩子,如果你输入 Cat(String name, Cat parent) - 那么你将 parent 分配给当前对象
    猜你喜欢
    • 2017-08-08
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多