gurghet
gurghet

Reputation: 7706

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?

Upvotes: 2

Views: 80

Answers (4)

The111
The111

Reputation: 5867

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
}

Upvotes: 4

Andy
Andy

Reputation: 518

Since class Animate is external you can't change it, but you can subclass it in your code:

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

public class Cat extends AnimatedWalk { ... }

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 149185

You cannot.

An interface just defines an API and does not enforce an implementation.

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 {
   ...
}

Upvotes: 1

Alexandru Severin
Alexandru Severin

Reputation: 6248

Make a class that extends Animate, has no extra methods and implements Walks (It would be identical to Animate, but it would be yours)

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

public class Cat extends MyAnimate {}

Upvotes: 3

Related Questions