2015-12-31 50 views
2

我有父子關係類和一個覆蓋方法,我想只顯示父類的方法。指向Child類Object的父類引用。只調用父類方法(JAVA)

class Parent{ 
    public void display(){ 
     System.out.println("Parent class display...."); 
    } 
} 
class Child extends Parent{ 
    public void display(){ 
     System.out.println("Child class display...."); 
    } 
} 

public class Demo { 
    public static void main(String... args) { 
     Parent parent = new Child(); 
     parent.display(); 
    } 
} 

所需的輸出: - 父類顯示....

這可能嗎?

+0

更好地添加到編程語言,你需要此工作標籤.... –

+1

見http://stackoverflow.com/questions/6896504/java-inheritance-calling-superclass-method –

+0

直接和您因爲您指的是Child對象,所以無法調用Parent方法。但是,您可以通過調用super.display() –

回答

1

直接,沒有。爲了讓進入超類實現,你必須以某種方式暴露它,否則它是外部不可見的。有幾種方法可以做到這一點。

子方法調用超級

你可以添加一個方法來Child調用Parent的實施display()

你將不得不投下您參考撥打電話:

((Child)parent).superDisplay(); 

注意添加一個方法Parent調用display()不會幫助,因爲它會叫Child.display(),因爲多態性Child實例。

當擴展擺動組件時,通常會使用與此技術相似的東西,其中子組件的實現通常會調用super.paintComponent()

反思

雖然往往表明糟糕的設計一個雜牌,反射會給你你想要什麼。只要得到Parent類的display方法並調用它在Child實例:

try { 
    Parent.class.getMethod("display").invoke(parent); 
} catch(SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException | ex) { 
    // oops! 
} 
-1

如果你只是在尋找一種方式,你可以宣佈你的display()方法是在兩個類static

public static void display(){ 
} 
+0

來打印「父級顯示....」99%的確定性,這對OP沒有任何幫助。 –

+0

日Thnx我得到了我的解決方案。 – user3297173