Inheritance and interfaces
JAVA
class Employee { protected String name; protected double salary; Employee(String name, double salary) { this.name = name; this.salary = salary; } double monthlyCost() { return salary; } } class Manager extends Employee { private double bonus; Manager(String name, double salary, double bonus) { super(name, salary); this.bonus = bonus; } @Override double monthlyCost() { return salary + bonus; } } public class Main { public static void main(String[] args) { Employee[] team = { new Employee("Sara", 9500), new Manager("Khalid", 18000, 3000) }; for (Employee e : team) { System.out.println(e.name + " " + e.monthlyCost()); } } }
Output
Sara 9500.0 Khalid 21000.0
extends makes Manager inherit everything from Employee, and @Override redefines a method. An Employee array holds both, and each object runs its own monthlyCost(). That is polymorphism.
An interface is a contract: it lists the methods a class must provide without saying how.
JAVA
interface Payable { double amountDue(); } class Invoice implements Payable { private double total; Invoice(double total) { this.total = total; } public double amountDue() { return total * 1.15; } } public class Main { public static void main(String[] args) { Payable p = new Invoice(1000); System.out.println(p.amountDue()); } }
Output
1150.0