24
Abstract class vs interfaces. When to use them?
"When we talk about abstract classes we are defining characteristics of an object type; specifying **what an object is." ~Jorge, 2017.
An abstract class is a "template" for classes, cannot be instantiated and should be extended by a class. It is used to define some common functionality across a set of related classes and allowing default method implementations.
Abstract classes are defined using the keyword abstract
. It can have both abstract and regular methods and can only be accessed in classes that inherit it.
public abstract class Animal {
public abstract void makeSound();
public void sleep() {
System.out.println("Zzz");
}
}
public class Dog extends Animal {
public void makeSound() {
System.out.println("Uff uff!");
}
}
public class Main {
public static void main(String[] args) {
Dog snoopy = new Dog();
snoopy.makeSound();
snoopy.sleep();
}
}
Different from interfaces, abstract class can have method implementations. This helps having code re-usability and to ensure that a class contains its expected behaviors, by extending an existing method or implementing an abstract method already defined in the abstract class.
Different from interfaces, abstract classes allow us to have encapsulated methods and attributes. It helps restricting direct access to the object's component and preventing unauthorized access to them.
"When we talk about an interface and define capabilities that we promise to provide, we are talking about establishing a contract about **what the object can do." ~Jorge, 2017.
An interface is a "contract" and should be implemented by a class*.* When a class implements **an interface, it must follow the behavior published by the interface. Interfaces generally defines properties and methods a class must have and unlike abstract class, **enable multiple inheritance.
Interfaces are defined using the keyword interface
. In languages like C# and Java, there is a standard convention to prefix all interfaces with an I
, so a file handler interface will be IFileHandler
.
public interface IWallet {
public void withdraw();
public void deposit();
double getBalance();
}
public class Wallet implements IWallet {
public void withdraw(){
//do something
}
public void deposit() {
//do something
}
double getBalance(){
//do something
}
}
It means that by implementing an interface, the class agrees to implement all of the functionality specified by the interface, ensuring that the expected behaviors are fulfilled.
Different from abstract classes, interfaces enables multiple inheritance in classes. It allow us to write assertive interfaces for a specific need. For example, we have an interface for a specific class and it can be reused in another class that combines two or more interfaces to achieve it's behavior.
Interfaces allow us to ensure functionality to classes in different contexts but with similar behavior.
24