构造函数将字段设置为默认值


package animal;
class AnimalHumanDogDemo
{
    public static void main(String[] args)
    {
        Animal chicken = new Animal(1.53, 53.2, 14.2, "red junglefowl");
        Human Alex = new Human(1.73, 62.3, 52.0, "Ape", "Greek", "Programmer", 1234);
        Dog Betty = new Dog(0.53, 21.6, 8.3, "wolf", "chiouaoua", 214, false, "white");
        String a = chicken.toString();
        System.out.println(a);
        double b = Alex.Yearly_salary();
        System.out.println(b);
        String c = Alex.toString();
        System.out.println(c);
        Boolean d = Betty.Expensive_Purebred();
        System.out.println(d);
        String e = Betty.toString();
        System.out.println(e);
    }
}

当我运行 main 时,字符串和 bollean 变量的结果总是为空,和"0"表示其他所有内容。我在动物,人类和狗类中创建了构造器,就像我一直在做的那样。如果需要,我可以提供类的代码。

您必须将变量存储在构造函数中。

public class Animal 
{
    private double x;
    private double y;
    private String des;
    public Animal(double x, double y, String des)
    {
        this.x = x;
        this.y = y;
        this.des = des;
    }
}

如cricket_007 x = x所述,可能会导致问题。

最新更新