简体   繁体   English

我怎样才能保证实现接口的类也扩展了类?

[英]How can I guarantee that a class that implements an interface also extends a class?

I have this code: 我有这个代码:

public class Animate {} // external api <--------------

public class Cat extends Animate {} // written by me

public interface Walks {} // also written by me

How can I enforce that if something walks it has to be animate? 我怎么能强制执行,如果有什么东西走,它必须是有生命的?

An abstract class can extend a class, and this is one of the rare situations where it could be useful. 抽象类可以扩展一个类,这是它可能有用的罕见情况之一。

abstract class AnimatedAbstractWalker extends Animate {

    // class gets concrete methods from Animate

    // and any abstract walk methods you want to add
    // (this replaces the Walk interface)
}

class Cat extends AnimatedAbstractWalker {
    // inherits standard animation implementation
    // you must implement walking like a cat
}

class Dog extends AnimatedAbstractWalker {
    // inherits standard animation implementation
    // you must implement walking like a dog
}

Make a class that extends Animate, has no extra methods and implements Walks (It would be identical to Animate, but it would be yours) 创建一个扩展Animate的类,没有额外的方法并实现Walks(它将与Animate相同,但它将是你的)

public class MyAnimate extends Animate implements Walks{} // your own Animate

public class Cat extends MyAnimate {}

You cannot. 你不能。

An interface just defines an API and does not enforce an implementation. 接口只定义API,不强制实现。

If you want that something both implements an interface and extends an implementation, just create an abstract base class doing both and extend from there : 如果你想要的东西都实现了一个接口并扩展了一个实现,只需创建一个抽象基类同时执行这两个操作并从那里扩展:

public class WalkingAnimate extends Animate implements Walks {
    public abstract ... // abstracts methods from Walks 
}

public class Cat extends WalkingAnimate {
   ...
}

Since class Animate is external you can't change it, but you can subclass it in your code: 由于Animate类是外部的,因此无法对其进行更改,但您可以在代码中对其进行子类化:

public abstract class AnimatedWalk extends Animate implements Walk {}  

In consequence, each class that inherits from your newly created AnimatedWalk is a Animate and has to implement Walk 因此,从新创建的AnimatedWalk继承的每个类都是Animate ,必须实现Walk

public class Cat extends AnimatedWalk { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM