Java 中的布尔字段输出不正确

Incorrect boolean field output in Java

我正在做初学者 Java 教程,并试图让 lovesCatnipisGuidedog 布尔字段在我的打印输出中打印为 true。我的代码运行,目前得到以下输出。

Name: Animal Weight: 100 Sex: M
Name: Cat Weight: 50 Sex: F Loves Catnip: false
Name: Dog Weight: 60 Sex: M Is Guide Dog: false

下面是我实现此输出的代码。涉及两个类。下面一个:

public class Animal {

    protected int weight; 
    protected String sex;
    protected boolean extra;

    public class Dog extends Animal{

        public Dog(int weight, String sex, boolean extra) {
            super(weight, sex, extra);
            this.extra = isGuideDog;
        }
        boolean isGuideDog;
    }

    public class Cat extends Animal{

            public Cat(int weight, String sex,boolean extra) {
            super(weight, sex, extra);
            this.extra = lovesCatnip;
        }
            boolean lovesCatnip;        
    }

    public Animal (int weight, String sex, boolean extra){
    this.weight =  weight;
    this.sex = sex;
    this.extra = extra;
    }
}

还有这个

import apollo.exercises.ch07_inheritance.Animal.Cat;
import apollo.exercises.ch07_inheritance.Animal.Dog;

public class AnimalRunner {
    public static void main(String[] animals) {

        Animal animal = new Animal(100, "M", false);

        Cat cat = animal.new Cat (50, "F", true);

        Dog dog = animal.new Dog (60, "M", true);

        System.out.println("Name: Animal Weight: " + animal.weight + " Sex: " + animal.sex);
        System.out.println("Name: Cat Weight: " + cat.weight + " Sex: " + cat.sex + " Loves Catnip: " + cat.lovesCatnip);
        System.out.println("Name: Dog Weight: " + dog.weight + " Sex: " + dog.sex + " Is Guide Dog: " + dog.isGuideDog);
    }
}

有人对我做错了什么有什么建议吗?

发生的情况是 Java 中的 booleandefault 值为 false,而您永远不会将值赋给isGuideDoglovesCatnip:

boolean lovesCatnip; // default: false

boolean isGuideDog;  // default: false  

我猜你想在你的构造函数中做这样的事情:

boolean lovesCatnip;
public Cat(int weight, String sex,boolean extra) {
    super(weight, sex, extra);
    this.extra = extra;       // <-
    this.lovesCatnip = extra; // <- I'm not 100% sure if this is the desired
}

对于Catclass是因为这一行:

this.extra = lovesCatnip;

不管 extra 的值是什么,当您创建 Cat 时,您总是将值 lovesCatnip 分配给它,并且由于您从未初始化它,它将成为 false.

现在,还有另一个问题,与属性的使用有关,如果您要创建 lovesCatnip,为什么您的 super-class 中有一个属性 extra在 subclass 中并将它们视为相同?

听起来你根本不需要超级 class 中的 extra

我相信

this.extra = lovesCatnip;

应该是

this.lovesCatnip = extra;

this.isGuideDog = extra;

您正在修改传入的参数(未将其分配给字段)。