无论发生什么情况,java实例变量都被设置为null
所以我试图创建一个对象“猫”,它有名字、重量和情绪。将Cat值分配给这些变量后,它只打印名称和权重,而不打印心情。它会说:“名字:猫,体重:10磅,情绪:空”,不管情绪是否有效
我以为这可能是变异基因的问题,但我找不到任何可以解决它的方法。更进一步,继承这个“Cat”类的类的属性也有这个问题,但它的新属性没有,所以它看起来像“Name:Cat,Weight:10lbs,Mood:null,Type:short hair”。为什么会这样
public class Cat extends Animal{
//Attributes
private String mood;
//Constructors
public Cat()
{
super();
this.mood = "no mood yet";
}
public Cat(String aName, double aWeight, String aMood)
{
super(aName, aWeight);
this.setMood(aMood);
}
//Accessors
public String getMood()
{
return this.mood;
}
//Mutators
public void setMood(String aMood)
{
if(aMood.equalsIgnoreCase("sleepy") || aMood.equalsIgnoreCase("playful") || aMood.equalsIgnoreCase("hungry"))
{
this.mood = aMood;
}
else
{
System.out.println("Invalid mood.");
}
}
//Other Methods
public String toString()
{
return super.toString() + " | Mood: " + this.mood;
}
public class Animal {
//Attributes
private String name;
private double weight;
//Constructors
public Animal()
{
this.name = "no name yet";
this.weight = 0.0;
}
public Animal(String aName, double aWeight)
{
this.setName(aName);
this.setWeight(aWeight);
}
//Accessors
public String getName()
{
return this.name;
}
public double getWeight()
{
return this.weight;
}
//Mutators
public void setName(String aName)
{
this.name = aName;
}
public void setWeight(double aWeight)
{
if (aWeight > 0.0)
{
this.weight = aWeight;
}
else
{
System.out.println("Invalid weight.");
}
}
共 (0) 个答案