有没有办法保证接口扩展Java中的类? [英] Is there a way to guarantee an interface extends a class in Java?

查看:99
本文介绍了有没有办法保证接口扩展Java中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下情况:

public abstract class Vehicle {
  public void turnOn() { ... }
}

public interface Flier {
  public void fly();
}

有没有办法可以保证任何实现<$ c的类$ c> Flier 还必须扩展 Vehicle ?我不想让 Flier 一个抽象类,因为我希望能够以类似的方式混合其他一些接口。

Is there a way that I can guarantee that any class that implements Flier must also extend Vehicle? I don't want to make Flier an abstract class because I want to be able to mix a few other interfaces in a similar manner.

例如:

// I also want to guarantee any class that implements Car must also implement Vehicle
public interface Car {
  public void honk();
}

// I want the compiler to either give me an error saying
// MySpecialMachine must extend Vehicle, or implicitly make
// it a subclass of Vehicle. Either way, I want it to be
// impossible to implement Car or Flier without also being
// a subclass of Vehicle.
public class MySpecialMachine implements Car, Flier {
  public void honk() { ... }
  public void fly() { ... }
}


推荐答案

Java接口不能扩展类,这是有道理的,因为类包含不能实现的实现细节在接口中指定..

Java interfaces cannot extend classes, which makes sense since classes contain implementation details that cannot be specified within an interface..

处理此问题的正确方法是通过转动 Vehicle 也进入了一个界面。 Car e.t.c.可以扩展 Vehicle 接口,强制程序员实现相应的方法。如果要在所有 Vehicle 实例之间共享代码,则可以使用(可能是抽象的)类作为需要实现该接口的任何类的父类。

The proper way to deal with this problem is to separate interface from implementation completely by turning Vehicle into an interface as well. The Car e.t.c. can extend the Vehicle interface to force the programmer to implement the corresponding methods. If you want to share code among all Vehicle instances, then you can use a (possibly abstract) class as a parent for any classes that need to implement that interface.

这篇关于有没有办法保证接口扩展Java中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆