簡體   English   中英

java中的繼承行為

[英]Inheritance behaviour in java

任何人都可以解釋,為什么這在eclipse中顯示錯誤,但運行成功沒有任何錯誤。我已粘貼下面的代碼。

家長班:

public class Parent {
    /*Parent class method*/
    public void show() { 
        System.out.println("Parent class show called");
    }
}

兒童班:

public class Child extends Parent {
    /* Child class overridden method*/  
    private void show() { 
        // this line show error in eclipse
        System.out.println("Child class show called ");
    }

    public static void main(String[] args) {
        Parent p = new Child();
        p.show();
    }
}

OutPut是:父類顯示調用

您不能通過繼承來降低方法的可見性。

因此,子類中的可見性必須是public而不是private

public class Child extends Parent{
/* Child class overridden method*/  
 public void show(){ // this line show error in eclipse
     System.out.println("Child class show called ");

 }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Parent p = new Child();
        p.show();

    }

}

發生這種情況是因為即使存在編譯錯誤,eclipse編譯器也可以創建類文件。 請點擊以下鏈接。

http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Fconcepts%2Fconcept-java-builder.htm

但是如果您將在java反編譯器中打開由此創建的子類,那么您將看到下面的代碼。

    public class Child extends Parent
    {
          private void show()
          {
              throw new Error("Unresolved compilation problem: Cannot reduce the visibility of the inherited method from Parent");
          }

          public static void main(String[] args)
          {
                Parent p = new Child();
                p.show();
          }
    }

所以基本上eclipse正在做什么,它忽略了這個錯誤並創建了一個帶有該錯誤的類文件,當存在類文件時,你可以運行你的代碼,因為在編譯時它能夠找出父有方法顯示所以它正在調用該方法。 但是如果你將引用從Parent更改為Child類,那么它將在運行時給你異常。

線程“main”中的異常java.lang.Error:未解決的編譯問題:無法在com.nucleus的com.nucleus.finnone.tbs.Child.show(Child.java:5)中減少來自Parent的繼承方法的可見性。 finnone.tbs.Child.main(Child.java:12)

您無法降低java中方法的可見性。 Child類中的show()方法必須是public 然后錯誤將消失,您應該輸出您的輸出Child class show called

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM