Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中通过继承类实现接口_Java_Class_Inheritance - Fatal编程技术网

在Java中通过继承类实现接口

在Java中通过继承类实现接口,java,class,inheritance,Java,Class,Inheritance,我有接口车: public interface Car { void run(); } 我还有一个实现此接口的基类: public class Base implements Car { @Override public void run() { //some implementation here } } 我还有一个类必须实现Car接口 那为什么我不能做这样的事呢 public class Der extends Base implement

我有接口

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
}

为什么我的基类不能实现接口?内部原因是什么?

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

当从
基类扩展时,您的
Der
当然会有
运行
方法,因为它实现了
Car
。所以

public class Der extends Base {

}
足够了

如果您需要覆盖
运行
,您可以很容易地做到这一点。代码看起来像

public class Der extends Base {

   @Override
   public void run() {
      //do whatever here
   }
}
如果您需要在使用
Car
的任何地方使用
Der
,您当然可以这样做

最后,如果您还需要
Car
来实现其他一些接口,那么语法将是

public class Der extends Base implements SomeInterface{

}

扩展
Base
时,您的
Der
类将有权访问
run
方法,并且实际上可以被视为
Car

即:


将完全有效。

这就是java中没有多重继承的原因

看看是否为
run
方法提供了实现,那么
基类的重写方法呢


因此,不允许冗余。

如果您的
基类
实现了
汽车接口
,并且该基类如果通过
Der class
扩展,则无需在Der class中再次实现汽车接口

好像

Class Base implements Car{

}
然后

Class Der extends Base{

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

Implements关键字应该位于示例中Extends关键字之后,如下所示:

    public class Der extends Base implements Car  {
          //no implementation of interface here because
          // Base class already implements it
    }
如果您在一个类中进行扩展和实现,甚至扩展已经实现了相同接口(如Car)的类(如Base),则不会出现问题

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
    }

它是
实现
,而不是
实现
。而
扩展
必须在
实现
之前。因此:
公共类Der extends Base implements Car
extends
必须在
implements
之前,例如,
公共类Der extends Base implements Car{
,但已经指出,这与使用
公共类Der extends Base相同{
您的
Base
类正在实现接口
Car
public class Der extends Base implements Car {
       //no implementation of interface here because Base class already implements it
    }