Inheritance and interfaces
extends, implements, overriding and polymorphism.
A class can extend one parent, and can implement many interfaces. An interface lists what a class must be able to do.
Java
interface Payable {
int pay();
}
abstract class Staff implements Payable {
protected final String name;
Staff(String name) {
this.name = name;
}
}
class Developer extends Staff {
Developer(String name) {
super(name);
}
@Override
public int pay() {
return 30000;
}
}
class Intern extends Staff {
Intern(String name) {
super(name);
}
@Override
public int pay() {
return 5000;
}
}
public class Main {
public static void main(String[] args) {
Staff[] team = {new Developer("Anu"), new Intern("Bala")};
for (Staff s : team) {
System.out.println(s.name + " " + s.pay());
}
}
}Output
Anu 30000 Bala 5000
The loop calls pay() on a Staff variable, and each object runs its own version. This is polymorphism, the most commonly asked object-oriented idea in interviews.
| Use | When |
|---|---|
Abstract class | Related classes share code and fields |
Interface | Unrelated classes share a capability |