无论如何,实例变量都设置为null

时间:2017-11-03 18:34:36

标签: java object

所以我试图创建一个对象" Cat"它有名字,重量和心情。将Cat值分配给这些变量后,它仅打印名称和重量,而不是心情。它会说:"姓名:猫,体重:10磅,心情:无效",无论情绪是否有效。

我认为这可能是变异器的一个问题,但我找不到任何可以修复它的东西。为了更进一步,该类的属性继承了这个" Cat" class也有这个问题,但它的新属性不是,所以它看起来像"名称:猫,体重:10磅,心情:null,类型:短发"。为什么会这样?

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 个答案:

没有答案