2
我正在做一个基于继承的概念的项目,并创建了一个超级构造函数,它内部有两个变量(String,int),这个超级构造函数然后在继承超级构造函数类的子构造函数中调用。然后我使用两种方法在构造函数中返回这些变量的属性。 age属性输出正常,但String属性返回null。下面的代码:构造函数中的变量是否返回null?
动物超一流
abstract public class Animal
{
int age;
String name;
Animal(String name, int age)
{
this.age = age;
this.name = name;
}
Animal()
{
this("newborn", 0);
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}
狼子类
public class Wolf extends Carnivore
{
String name;
int age;
Wolf(String name, int age)
{
this.name = name;
this.age = age;
}
Wolf()
{
super();
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
主要方法类
public class Main {
public static void main(String[] args)
{
Wolf newWolf = new Wolf();
System.out.println("Name = " + newWolf.getName());
System.out.println("Age = " + newWolf.getAge());
}
}
年龄正在返回0,这是正确的,但System.out.println("Name = " + newWolf.getName());
似乎是返回null而不是“新生儿”。感谢您解决此问题的任何帮助。
更新 - 我需要的,我并没有包括在这个例子中另一个构造的getName()
方法,以便有没有办法让它们同时存在?
删除指定的字段定义中删除了'的getName()'从'Wolf'方法,即返回狼'值.name',你从来没有设置过,删除'Wolf.name'也一样(在'Wolf'中'getAge()'和'age') –
你被欺骗了,'age'没有返回0你认为它正在返回,它正在返回默认状态t'int'值,它恰好为0.它不是在'Animal'的构造函数中指定的值。 – Tunaki
问题是,我有另一个需要getName()方法的构造函数。 – Tom