继承和接口

Jon*_*now 10 java inheritance interface subclass

当涉及接口时,我一直在尝试理解继承.我想知道子类是如何创建的,如果它们遵循以下内容:

例如,假设我有:

  1. 一个实现接口I的超类
  2. 和一对扩展超类A的子类

我的问题

  1. 我是否必须在扩展A的所有子类中提供接口方法'q和r'的实现?

  2. 如果我不在子类中提供接口的实现,我是否必须使该子类成为抽象类?

  3. 任何子类都可以实现我吗?例如,C类扩展A实现I,这可能吗?即使它已经扩展了一个实现我的超类?

  4. 假设我没有从接口I提供方法r的实现,那么我将不得不制作超类A和抽象类!那是对的吗?

我的示例代码:

    //superclass
    public class A implements I{
    x(){System.out.println("superclass x");}
    y(){System.out.println("superclass y");}
    q(){System.out.println("interface method q");}
    r(){System.out.println("interface method r");}
    }

    //Interface
    public Interface I{
    public void q();
    public void r();
    }

    //subclass 1
    public class B extends A{
    //will i have to implement the method q and r?
    x(){System.out.println("called method x in B");}
    y(){System.out.println("called method y in B");}
    }

    //subclass 2
    public class C extends A{
    //will i have to implement the method q and r?
    x(){System.out.println("called method x in C");}
    y(){System.out.println("called method y in C");}
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*rth 7

1)不,您不需要在子类中实现这些方法,因为它们已经在超类中定义.子类将继承那些方法定义.

2)不,请参阅1.唯一的例外是如果超类是抽象的并且没有实现接口,那么如果子类不是抽象的,则需要在子类中实现它.

3)不可以.它可以正确编译,但不起作用,所以不应该这样做.

4)是的,这是正确的.如果未从接口实现方法,则需要使类成为抽象.