2014-01-18 128 views
-2

我有一個有點brainfart對我的基本知識傳承:從接口變量繼承?

public interface IDrawable 
{ 
    public double x, y; 
    object GetDrawable(); 
} 

public class Beacon : IDrawable 
{ 
    public Beacon(string id, double x, double y) 
    { 
     this.id = id; 
     this.x = x; 
     this.y = y; 
    } 
} 

爲什麼沒有燈塔的構造能夠找到它的父定義的雙打x和y?

+2

編寫代碼並嘗試提問之前,你的代碼甚至不會編譯! –

回答

4

代碼不編譯,因爲:

錯誤1接口不能包含字段

接口是有關操作(包括性),它們不能包含數據。你可以在這裏使用性質,但他們必須在你的類來實現:

public interface IDrawable 
{ 
    double x { get; set; } 
    double y { get; set; } 
    // ... 
} 

public class Beacon : IDrawable 
{ 
    public double x { get; set; } 
    public double y { get; set; } 

    public Beacon(string id, double x, double y) 
    { 
     // ... 
     this.x = x; 
     this.y = y; 
    } 
} 

如果你的基類必須包含此數據,使它成爲一個抽象類:

public abstract class Drawable 
{ 
    public double x { get; set; } 
    public double y { get; set; } 
    public abstract object GetDrawable(); 
} 

public class Beacon : Drawable 
{ 
    public Beacon(string id, double x, double y) 
    { 
     //this.id = id; 
     this.x = x; 
     this.y = y; 
    } 

    public override object GetDrawable() 
    { 
     // ... 
    } 
} 

因此最終的結論是 - 閱讀關於接口與抽象類的區別,並決定應採取哪種方式。

+0

Aha,duh。我明顯在研究和管理方面花費了太長時間,忘記了基本的實施細節。謝謝! – Benjin

3

這不應該編譯。您必須在接口中聲明x和y作爲屬性,並在您的實現中實現getter和setter。