Reputation: 6236
Assume an abstract class has only abstract methods declared in it and the interface has abstract methods.
How does this affect the abstract method m
?
abstract class A {
abstract void m();
}
interface A {
abstract void m();
}
Upvotes: 0
Views: 108
Reputation: 1583
Interfaces are also more useful when you don't exactly know if all your entities will need to override a specific method. Consider for instance birds, some can fly and some can't. You don't want to force overriding a fly()
method in all Bird
subclasses.
public abstract class Bird(){
...
public abstract void eat(); //all birds eat
public abstract void sleep(); //all birds sleep
public abstract void fly(); //is wrong here since not all birds can fly
}
A more correct way would be to define interfaces for specific cases, so in this case
public interface Flyable{
abstract void fly();
}
Then you can define your subclasses as birds that can fly or not based on the fact they implement the Flyable
interface or not.
public class Eagle extends Bird implements Flyable{
@override
public void fly(); //needed
-----
}
public class Ostrich extends Bird{
//does't fly
}
Upvotes: 1
Reputation: 115328
Even if the abstract class is a pure abstract, i.e. contains only abstract methods and does not contain state, your subclass extends
this class and therefore you have single inheritance only.
However you can implement several interfaces.
Therefore if you want to force your classes to be a subclass of your A
and not to be subclass of something else, use abstract class. Otherwise define interface.
Upvotes: 3