簡體   English   中英

Java:Interface方法的重寫

[英]Java :Interface Method's Overriding

package chap8;  
 interface Interfaces
 {
     void nMethod();    //   normal method of interface

     default void dMethod() // default method of interface
     { System.out.println("Default Method of Interface"); }

     static void sMethod()  // static method of interface
     { System.out.println(" static method of interface"); }

 } 
 class IClass implements Interfaces
 { 
   public void nMethod()
    { System.out.println("Normal Method of Interface in IClass ");}
    static void sMethod()
    { System.out.println("Does function overrided ?");}
    public void dMethod()
    { System.out.println("default Method of Interface in IClass ");}
 }
 class MainClass
 {
     public static void main(String args[])
     {
        IClass ob =new IClass();

        ob.nMethod();
        ob.sMethod(); // overrided method ??
        ob.dMethod();

        // calling static

         //Interfaces.sMethod //  via Interfaces
        // IClass.sMethod();   // via IClass       (why all these sMethod calling showing error)



     }
 } 

問題:a)接口中聲明的sMethod是否被IClass中存在的sMethod覆蓋?

b)為什么我不能通過接口和IClass調用sMethod?

THPR FPR的幫助!

有關默認方法和靜態方法,請參考oracle文檔。

擴展包含默認方法的接口

擴展包含默認方法的接口時,可以執行以下操作:

  1. 完全不提默認方法,它使您的擴展接口可以繼承默認方法。
  2. 重新聲明默認方法,使其抽象。
  3. 重新定義默認方法,該方法將覆蓋它

關於您的查詢:

  1. 如果將這些概念應用於示例,則dMethod overridden IClass
  2. sMethod()IClass隱藏sMethod()Interfaces

簡化您的例子

public class A {
    interface I {
        static void sMethod() {
            System.out.println("In the interface I");
        }
    }
    static class C implements I {
        void sMethod() {
            System.out.println("In the class C");
        }
    }
    public static void main(String[] args) {
        I.sMethod();
        new C().sMethod();
    }
}

版畫

In the interface I
In the class C

IClass中是否存在被sMethod覆蓋的接口中聲明的sMethod?

static方法是隱藏的,而不是被覆蓋。 這意味着在特定的類上調用靜態方法,您將始終獲得比方法更多的信息,因為它將不遵循繼承,並為您提供了一個被重寫的方法(實際上,它不能,因為它不使用實例)

為什么我無法通過Interface和IClass調用sMethod?

我不清楚,請參見上面的示例,其中的單詞符合預期。

您不能再打電話給他們。

澄清@Hulk的評論。 您不能通過實例調用它們,但是可以通過實現它們的classinterface來調用它們。

暫無
暫無

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

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