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

2024-04-21

我正在基于继承进行分配,并且创建了 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."); 
    }
}

Wolf

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,但我不太清楚为什么。这是我第一次使用多个构造函数,所以我对它的工作原理有点困惑,所以任何帮助将不胜感激,谢谢。


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

Your Wolf and Carnivore构造函数应该是:

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

原因是,您正在设置local每种类型的实例变量,但调用getAge()超类的方法 - 这是获取超类的值age,其值实际上并未被分配到任何地方,并且被赋予默认值0。这对于name,默认为null.

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何正确配置多个构造函数? 的相关文章

随机推荐