2014-02-17 169 views
-2

考慮一個帶有一些變量的父類a,b,c。如果我從這個父類派生一個子類,子類是否知道變量a,b,c?如果是這樣,a,b,c的值是否在這個子類中保持不變?繼承的基礎知識

+0

請重新考慮您的問題,或者至少發佈您的代碼,如果可能的話。 – Ademar

回答

0

子類將包含父類變量。

如果子類可以訪問它們是另一回事。變量需要至少有一個受保護的可訪問性,以便子類能夠訪問和/或使用它們。

+0

如果將這些變量聲明爲私有? –

+0

您不能從子類訪問它們,只能從父類中訪問它們。您可以在父類中創建一個公用函數來設置專用字段。 – martijn

2

OOP語言有來自外部和內部的類確定字段的可見性(「變量」)不同的訪問級別。 大部分面向對象程序設計語言至少有以下三種:private,protectedpublic。如果你的基類變量是private,派生類不能看到他們,如果他們是protected他們可以(但非派生類不能),如果他們是public每個人都可以看到他們 - 包括衍生和非相關的類。

當然,在基類的方法可以基類總是訪問私有變量 - 即使在派生類中新加入的方法無法看到它們。這裏是C++中的一個例子(其他OOP語言具有相似的語法)。

class Base { 
    private: 
    int a; 
    protected: 
    int b; 
    public: 
    int f() { a = 1; return a + b; } 
} 

class Derived : public Base { 
    public: 
    int g() { 
     // You cannot access a here, so this is illegal: 
     a = 2; 

     // You can access b here, so this is legal: 
     b = 2; 

     // Base::f, or parent::f() in Java, can access a, so this will return 1 + 2 = 3. 
     return Base::f(); 
    } 
} 

class NonRelated { 
    void h() { 
    Derived d; // Create a derived object 

    // Both of these are illegal since neither a nor b is public: 
    d.a = 3; 
    d.b = 4; 

    // You *can* call both f() and g(), because they are both public. 
    // This will return 3. 
    // (Side note: in actual C++, calling d.f() would not be a good idea since a is not initialized). 
    d.g(); 
    } 
} 
+0

這些變量的值會在子類中保持不變嗎? –

+0

我明白你在做什麼,但問題不明智。子類沒有變量的另一個副本:它擴展了基類,這意味着它繼承了它的所有變量和函數,但是如果實例化它,則不會獲得Base類的實例和Base + Derived類的實例, 或類似的東西。 – CompuChip