在Java中通过继承的Class实现接口

时间:2014-06-12 06:53:31

标签: java class inheritance

我有界面Car

public interface Car {
    void run();
}

我还有一个实现此接口的基类:

public class Base implements Car {
    @Override
    public void run() {
        //some implementation here
    }
}

另外我还有一个必须实现Car接口的类 那么为什么我不能做那样的事呢?

public class Der extends Base implements Car  {
   //no implementation of interface here because Base class already implements it
}

为什么我的基类无法实现接口?这是什么内部原因?

7 个答案:

答案 0 :(得分:4)

Base消费时,您的Der当然会使用run方法,因为它会实现Car。所以

public class Der extends Base {

}

就足够了

如果您需要覆盖run,则可以轻松完成此操作。代码看起来像

public class Der extends Base {

   @Override
   public void run() {
      //do whatever here
   }
}

如果您需要在使用Der的任何地方使用Car,您当然可以这样做。

最后,如果您需要Car同时实现其他接口,则语法为

public class Der extends Base implements SomeInterface{

}

答案 1 :(得分:1)

如果您的Base class已实施Car Interface而此基类(如果Der Class扩展),则无需再次在Der类中实现Car接口。

喜欢如果

Class Base implements Car{

}

然后

Class Der extends Base{

}

然后,接口中的所有方法都会在Der类中隐式访问。

答案 2 :(得分:1)

public class Der implements Car extends Base {
   //no implementation of interface here because Base class already implements it
}

在实现keywork之前必须使用extends关键字

对:

public class Der extends Base implements Car {
       //no implementation of interface here because Base class already implements it
    }

答案 3 :(得分:0)

基类(Der的超类)已经实现了Car接口,因此不需要显式实现它。

答案 4 :(得分:0)

延长Base时,您的Der课程可以访问run方法,并且实际上可以被视为类型Car

即:

Car a = new Der(); 

完全有效。

答案 5 :(得分:0)

这就是为什么java中没有多重继承的原因。

看看您是否提供了run方法的实现,那么覆盖Base Class的方法

所以不允许冗余。

答案 6 :(得分:0)

Implements 关键字应位于示例中的扩展关键字之后,如下所示:

    public class Der extends Base implements Car  {
          //no implementation of interface here because
          // Base class already implements it
    }

如果你在一个类中执行extends和implements,即使扩展了类,即已经实现了相同接口的Base,即Car,也没有问题。