Module 3: Object-Oriented Programming
Abstraction and Interfaces
Define contracts and expose essential behaviour in Java.
Abstraction exposes the behaviour a caller needs while hiding unnecessary implementation details. In Java, abstract classes and interfaces are two common ways to express abstractions.
Abstract classes#
An abstract class cannot be instantiated directly. It can contain fields, constructors, concrete methods, and abstract methods that subclasses must implement when they are concrete.
abstract class Shape {
abstract double area();
void describe() {
System.out.println("I am a shape");
}
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
Interfaces#
An interface defines a contract that a class agrees to implement. A class can implement multiple interfaces, which is useful when a type needs several independent capabilities.
interface Printable {
void print();
}
class Report implements Printable {
@Override
public void print() {
System.out.println("Printing report");
}
}
Interface methods that are implicitly abstract and public must be implemented with public visibility. Modern Java interfaces can also contain default and static methods.
Abstract class or interface?#
Choose an abstract class when related types need shared state or a common base implementation. Choose an interface to express a capability or contract that unrelated classes can implement. They can also be used together.
Practice#
Create a Playable interface with a play() method. Implement it in two classes, such as VideoPlayer and AudioPlayer, then call them through variables of type Playable.