Interfaces simply define the contract (API) of the class. In other words, it simply states which methods you MUST implement if your class implements the interface.
With Abstract classes, you can implement functionality. This is usually done when multiple classes have similar functionality, so the implementation only needs to be done once.
Another differnce between the two is that a class my implement many interfaces, but can extend only one abstract class (multiple inheritance). This is because interfaces don't define implementation. If you could extend multiple abstract classes, the JVM would not know which implementation from which abstract class to use.
Example of using an interface:
public interface Bouncable {
public void bounce(); // no implementation
}
public class Ball implements Bouncable {
// now you must provide the implementation
public void bounce() {
System.out.println("I can bounce!");
}
}
But let's say you have more than one object that can bounce, and you don't want to write the implementation more than once.
Example of using abstract class:
public abstract class BouncableObject {
// you can provide implementation
public void bounce() {
System.out.println("I can bouce too!");
}
// or not if you define it abstract
public abstract void sayMyName();
}
// you don't need to implement bounce()
public class Ball extends BouncableObject {
// but you have to give this implementation
public void sayMyName() {
System.out.println("I am a ball");
}
}
public class RubberChicken extends BouncableObject {
public void sayMyName() {
System.out.println("I am a rubber chicken");
}
}
And now both Ball
and RubberChicken
can call bounce()