【问题标题】:OOP interface inheritanceOOP接口继承
【发布时间】:2015-10-12 02:12:46
【问题描述】:

我的问题是一个接口可以扩展另一个接口还是实现另一个接口。

interface A {
}

interface B extends A {
}

OR 

interface B implements A {
}

【问题讨论】:

标签: java oop inheritance


【解决方案1】:

除非有 Java 8 扩展,interface 不会实现任何东西。

因此,extends 是正确的术语。

【讨论】:

    【解决方案2】:

    一个接口只能扩展另一个接口,因为一个接口不能包含任何实现。

    interface ParentInterface{
        void myMethod();
    }
    
    interface SubInterface extends ParentInterface{
        void anotherMethod();
    }
    

    【讨论】:

      【解决方案3】:

      就“接口”的继承而言,它们总是扩展它们从不实现任何东西。

      【讨论】:

        【解决方案4】:

        是的,它们可以通过extends 关键字,因为接口不能实现任何方法,只能声明它们的签名。

        interface A {
            public void foo();
        }
        
        interface B extends A {
            // You don't implement the methods from A here
            public void bar();
        }
        
        class C implements B {
            public void foo(){
            }
            public void bar(){
            }
        }
        

        任何实现B 的类也必须实现A 中的方法。

        【讨论】:

        • Sam 他在询问一个类可以始终实现的接口,但他在询问的是接口。
        • @KulbhushanSingh 是的,我解释了接口
        • 好的...实际上你是在课堂上实现它所以只是指出来。
        • @KulbhushanSingh 不管我给一个类的例子是不是题外话,我还是解释了接口的相关细节
        【解决方案5】:

        是的,一个接口可以在 Java 中扩展另一个接口。

        // this interface extends from the Body interface:
        public interface FourLegs extends Body
        {
          public void walkWithFourLegs( );
        
        }
        

        好吧,但我们必须思考,

        我们什么时候需要一个接口来扩展另一个接口

        我们知道任何实现接口的类都必须实现在该接口中声明的方法标题。而且,如果该接口从其他接口扩展而来,那么实现类还必须实现正在扩展或派生的接口中的方法

        因此,在上面的示例中,如果我们有一个实现 FourLegs 接口的类,那么该类必须定义 FourLegs 接口和 Body 接口中的任何方法标题。

        问题第二部分:接口不要实现另一个接口,因为

        Implements 表示为接口的方法定义一个实现。但是接口没有实现,所以这是不可能的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-19
          • 1970-01-01
          • 2021-06-25
          • 1970-01-01
          • 2016-06-25
          • 2018-05-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多