Java抽象构造函数问题
问题描述:
我在理解抽象构造函数的工作方面存在问题。我知道一个抽象的超类是像背骨和所有的子类必须有方法放在它,但我不明白构造方。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;
这样你就不会既没有重复的代码或编译错误。
+0
啊我明白了。我知道我必须把这些田地放在某个地方,但现在这是有道理的。超级只是引用回已经分配了什么人口等的超类。谢谢 – Softey
答
在Monkey
类构造函数中初始化之前,您正在访问Abstract类变量(name,year_discovered,population
)。像下面一样使用
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是静态的每个子动物可以定义猴构造函数:
public Monkey(String type, String color){
super("Monkey",1900,"100000");
this.type = type;
this.color = color;
}
哪里都是你的名字,year_discovered,人口在子类或构造域? 。在创建它之前,你不能访问父项的那些字段(即,在它的构造函数被调用之前)。 – TheLostMind
'我试图在调用它之前引用超类型构造函数---不,你试图在超类型构造函数完成之前引用超类型*字段*。 –
啊,我想我必须把:public String name; public int year_discoovered; public String population;在实际的猴类,以及完全不保存代码嗯 – Softey