2014-02-07 144 views
0

我在理解抽象構造函數的工作方面存在問題。我知道一個抽象的超類是像背骨和所有的子類必須有方法放在它,但我不明白構造方。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;} 
       } 

我得到一個錯誤消息,說我想在調用它之前引用超類型構造函數。

現在我這樣做的原因是,我不必爲每個不同的物種重複代碼。代碼僅僅是我嘗試幫助我解決困惑的一個簡單例子。感謝您未來的回覆。

+0

哪裏都是你的名字,year_discovered,人口在子類或構造域? 。在創建它之前,你不能訪問父項的那些字段(即,在它的構造函數被調用之前)。 – TheLostMind

+3

'我試圖在調用它之前引用超類型構造函數---不,你試圖在超類型構造函數完成之前引用超類型*字段*。 –

+0

啊,我想我必須把:public String name; public int year_discoovered; public String population;在實際的猴類,以及完全不保存代碼嗯 – Softey

回答

4

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

2

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; 
2

並使您的領域從類私人不公開。

1

如果用戶名和year_discovered是靜態的每個子​​動物可以定義猴構造函數:

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