Java 抽象构造函数问题



我在理解抽象构造函数的工作原理方面遇到了问题。我知道一个抽象的超类就像骨干一样,所有的子类都必须在其中放置方法,但我不了解构造函数方面。

 public abstract class Animal{
           public String name;
           public int year_discovered; 
           public String population; 
 public Animal(String name, int year_discovered, String population){
           this.name = name;
           this.year_discovered = year_discovered;
           this.population = population; }
           }

上面是我的超级抽象类。下面是我的子类。

 public class Monkey extends Animal{
           public String type;
           public String color;
 public Monkey(String type, String color){
           super(name,year_discovered,population)
           this.type = type;
           this.color = color;}
               }

收到一条错误消息,说我正在尝试在调用超类型构造函数之前引用它。

现在我这样做的原因是我不必为每个不同的物种复制代码。代码只是我制作的一个快速示例,以帮助我解决我的困惑。感谢您以后的任何回复。

您的Monkey类构造函数应如下所示:

 public Monkey(String name, int year_discovered, String population, String type, String color){
           super(name,year_discovered,population);
           this.type = type;
           this.color = color;

这样,您就不会有重复的代码或编译错误。

您正在访问抽象类变量 ( name,year_discovered,population ),在它们在Monkey类构造函数中初始化之前。像下面这样使用

public Monkey(String name, int year_discovered, String population, 
                            String type, String color){
           super(name,year_discovered,population);
           this.type = type;
           this.color = color;

并将类中的字段设为私有而不是公共字段。

如果每个子动物的名称和year_discovered是静态的,则可以将 Monkey 构造函数定义为:

public Monkey(String type, String color){
       super("Monkey",1900,"100000");
       this.type = type;
       this.color = color;
}

最新更新