我正在做一个基于继承的任务,并且我创建了两个假设做不同事情的构造函数。一个构造函数没有任何参数,应该生成一个预定义的值,另一个构造函数有两个参数,它们由名称和类型为String和int的年龄组成。我以某种方式重新配置了这两个构造函数,这样它们都不会产生他们应该做的。下面是这些构造函数在调用的类:如何正确配置多个构造函数?
动物(超类)
abstract public class Animal implements Comparable<Animal>
{
int age;
String name;
Animal(String name, int age)
{
this.age = age;
this.name = name;
}
Animal()
{
this("newborn", 0);
}
public int getAge()
{
return age;
}
public void setName(String newName)
{
name = newName;
}
String getName()
{
return name;
}
}
食肉动物
public class Carnivore extends Animal
{
Carnivore(String name, int age)
{
this.age = age;
this.name = name;
}
Carnivore()
{
super();
}
@Override
public int compareTo(Animal o)
{
//To change body of generated methods, choose Tools | Templates.
throw new UnsupportedOperationException("Not supported yet.");
}
}
狼
public class Wolf extends Carnivore
{
String name;
int age;
Wolf(String name, int age)
{
this.name = name;
this.age = age;
}
Wolf()
{
super();
}
String getName()
{
return name;
}
}
主要方法
System.out.println("************1st constructor of Wolf************");
Wolf wolfExample = new Wolf("Bob", 2) {};
System.out.println("Name = " + wolfExample.getName());
System.out.println("Age = " + wolfExample.getAge());
System.out.println("************2nd constructor of Wolf************");
Wolf newWolf = new Wolf();
System.out.println("Name = " + newWolf.getName());
System.out.println("Age = " + newWolf.getAge());
实际输出
************1st constructor of Wolf************
Name = Bob
Age = 0
************2nd constructor of Wolf************
Name = null
Age = 0
期望输出
************1st constructor of Wolf************
Name = Bob
Age = 2
************2nd constructor of Wolf************
Name = newborn
Age = 0
第二构造函数的年龄正在返回其默认值和名称一个也返回null,但我不太确定为什么。这是我第一次使用多个构造函数,所以我有点困惑,因为它的工作原理,所以任何帮助将不胜感激,谢谢。
请看贴[MCVE]以获得更快速的帮助! –
这是你正在做的这个(“新生儿”,0);' –