Abstract classes can have method in them, while interfaces cannot have them.
I usually think of it like this:
- If you want a class to force other classes to write methods, use an interface.
- If you want a class to hold a common method for multiple classes, use an abstract class.
So for example, you might want to make an Animal
class. And then have a Dog
and Cat
class. Both dogs and cats sleep. So you'd want them both to have a sleep method. And they sleep essentially the same way. So you'd want the Animal
class to hold the method (since it's the same for Dog
and Cat
.
public abstract class Animal {
public void sleep() {
//make ZZZZ appear in the air or whatever
}
}
public class Dog extends Animal {
//This class automatically has the sleep method
}
public class Cat extends Animal {
//This class automatically has the sleep method
}
On the other hand, say you had a Snake
and Shark
class. Both snakes and sharks attack, but in different ways (venom vs bitting). So you might have a Attacker
interface.
public interface Attacker {
//We HAVE to have this here
public void attack(); //Note - we didn't write the method here, just declared
}
public Snake implements Attacker {
//We HAVE to have this here
public void attack() {
//inject venom
}
}
public Shark implements Attacker {
public void attack() {
//rip apart
}
}
Note that abstract classes can also have non-defined methods (like an interface). So you could have public void makeMeanSound();
in Animal
and then have the Dog
growl and the Cat
hiss. The main difference is that abstract classes can write actual methods.
Interface - force methods to be written (i.e. force Snake
and Shark
to have the attack()
method).
Abstract class - provide common methods to subclasses.