繁体   English   中英

如何正确配置多个构造函数?

[英]How to correctly configure multiple constructors?

我正在做一个基于继承的赋值,我已经创建了2个构造函数,这些构造函数可以用来做不同的事情。 一个构造函数没有任何参数并且应该生成预定义的值,另一个构造函数有2个参数,这些参数由名称和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但我不太清楚为什么。 这是我第一次使用多个构造函数,所以我有点困惑,因为它有用,所以任何帮助都会非常感激,谢谢。

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

你的WolfCarnivore构造者应该是:

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

原因是,您要为每种类型设置本地实例变量,但调用超类的getAge()方法 - 这是获取超级的age值,其值实际上并未在任何地方分配,并且默认值为0 name相同,默认为null

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM