Abstract Class and Interface
| Abstract Class | Interface |
|
Abstract class can contain fields and methods that implement default behavior, and can also have abstract methods. |
Interface can only contain constants (public static and final variables) and method signatures (method without body / abstract method). |
Abstract Class
Abstract class are used to declare common characteristics of subclasses, and can contain fields and methods that describe the actions that a class can perform. But abstract class cannot be instantiated, they can only be subclassed.
Why make a class if you can’t make objects out of it? Because the class might be too.. abstract.
For example, an abstract class Passenger. In real, we might want to make object of passenger with more concrete form, like Adult passenger or Infant passenger. But both adult and infant, are passenger sharing the same default characteristic.
An abstract class can include methods that contain no implementation. These are called abstract methods. The subclass must define an implementation for every abstract method of the abstract superclass.
For example, an abstract class Passenger, having the characteristics of name, gender, and method earningTravelPoint, and abstract method isSeatAvailable.
abstract class Passenger {
|
Each non-abstract subclass of Passenger, such as AdultPassenger and InfantPassenger will have the same fields of name, gender, travelPoint and able to perform method earningTravelPoint, but also must provide implementation for the abstract method isSeatAvailable:
class AdultPassenger extends Passenger {
|
Interface
An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. Interface defining what a class “can do” without any explanation “how the class will do it“.
Interface usually creating a set of methods without any implementation, and the implementation must be overridden by the implemented class. The advantage is that it provides a flexible way for any class, from any inheritance tree, to have the same common characteristic, and can implement one or more interfaces.
public interface FrozenYoghurt {
|
Class that implements the interface must provides a method body for each of the methods declared in the interface.
public class GreenMango implements FrozenYoghurt {
|
As we can see above, the interface FrozenYoghurt and interface SnowIce define what class can do in general. And then, class GreenMango and ColdDessert can implement those interface and having common methods without any relation one to another, and able to define their own implementation of the method.
References :