Abstract Classes and Interfaces
An abstract class cannot be instantiated and may contain abstract methods without a body that children must implement. An interface is a pure contract: a class can implement many interfaces. Interfaces can have default methods with a body.
Example
interface Payable {
double pay();
default String label() { return "Payment"; }
}
abstract class Employee implements Payable {
String name;
Employee(String name) { this.name = name; }
}
class Teacher extends Employee {
Teacher(String n) { super(n); }
public double pay() { return 5000; }
}
public class Main {
public static void main(String[] args) {
Teacher t = new Teacher("Ada");
System.out.println(t.name + ": " + t.label() + " " + t.pay());
}
}Result
Ada: Payment 5000.0
Exercise
A class promises to follow an interface with...
class A Payable {}
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.