【问题标题】:Java :Interface Method's OverridingJava:接口方法的覆盖
【发布时间】:2016-08-12 13:51:24
【问题描述】:
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) 为什么我无法通过 Interface 和 IClass 调用 sMethod?

感谢 fpr 帮助!!!

【问题讨论】:

    标签: java methods interface static overriding


    【解决方案1】:

    请参阅有关 default methods 和静态方法的 oracle 文档。

    扩展包含默认方法的接口

    当您扩展包含默认方法的接口时,您可以执行以下操作:

    1. 根本不提默认方法,让你的扩展接口继承默认方法。
    2. 重新声明默认方法,使其抽象化。
    3. 重新定义默认方法,它会覆盖它

    关于您的查询:

    1. 如果您将这些概念应用到您的示例中,您的 dMethodIClass 中是 overridden
    2. IClass 中的 sMethod() 隐藏 Interfaces 中的 sMethod()

    【讨论】:

      【解决方案2】:

      简化你的例子

      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
      

      接口中声明的 sMethod 是否被 IClass 中的 sMethod 覆盖?

      static 方法被隐藏,而不是被覆盖。这意味着在特定类上调用静态方法,你总是会得到比方法,因为它不会遵循继承并给你一个覆盖的方法(实际上它不能因为它不使用实例)

      为什么我无法通过Interface和IClass调用sMethod?

      这对我来说不是很清楚,请参阅上面的示例,哪些单词符合预期。

      你不能再打电话给他们了。

      澄清@Hulk 的评论。您不能通过实例调用它们,但可以通过实现它们的classinterface 调用它们。

      【讨论】:

      • @ Peter Lawrey 据我所知静态方法不能被覆盖,那么为什么在这里发生覆盖?
      • @Lalitkumar 我错过了,需要修改。
      • @Hulk 为什么 sMethod(which is static) 不能通过 classname.staticmethodname 过程调用?
      猜你喜欢
      • 2014-07-17
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2014-05-23
      • 2013-11-14
      • 2015-10-31
      • 2014-10-23
      • 1970-01-01
      相关资源
      最近更新 更多