2016-11-28 16 views
3

我正在做一个基于继承的任务,并且我创建了两个假设做不同事情的构造函数。一个构造函数没有任何参数,应该生成一个预定义的值,另一个构造函数有两个参数,它们由名称和类型为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,但我不太确定为什么。这是我第一次使用多个构造函数,所以我有点困惑,因为它的工作原理,所以任何帮助将不胜感激,谢谢。

+0

请看贴[MCVE]以获得更快速的帮助! –

+0

这是你正在做的这个(“新生儿”,0);' –

回答

3

你的基类似乎是正确的,但你需要改变你的实现。

WolfCarnivore构造函数应该是:

Wolf(String name, int age) 
{ 
    super(name, age); 
} 

原因是,你正在为每种类型的当地实例变量,但在调用父类的getAge()方法 - 这是获得超级的价值age,其价值实际上没有被分配到任何地方,并且被给予默认值。这与name相同,默认为null

您需要使用传递的变量调用super,并且不需要为每个扩展对象重新定义它们。

+0

这工作,谢谢。 – user7128699

+0

ahahah,我只是通过_everything_重新阅读,看看为什么它不会基于你最后的评论;)很高兴听到它,快乐的编码!请务必upvote /接受有用的答案:) –

+0

知道你不需要在_Wolf_either中重写'getName',在这个对象上调用它将使用基类中定义的方法/变量值。 –

相关问题