Module 2 ยท Objects and collections Lesson 5 of 15
Inheritance, interfaces and why service companies ask
Inheritance shares behaviour from a parent class; an interface is a contract a class promises to keep. "Why is an interface better than an abstract class here?" is a standard first-round question.
The concept
Inheritance extends a class: class SavingsAccount extends Account inherits the fields and methods and can override behaviour. An interface declares what a class can do โ interface Payable { double calculatePay(); } โ and any class implementing it must supply the method, which is how unrelated types join a common contract.
In practice interfaces age better than inheritance. A class can implement many interfaces and extend only one, so a design built on interfaces stays changeable. The phrase to remember in an interview: prefer composition and interfaces, use inheritance for genuine is-a relationships.
interface Payable {
double amount();
}
abstract class Worker {
abstract String role();
}
class Intern extends Worker implements Payable {
public String role() { return "intern"; }
public double amount() { return 15000; }
}
// Java has no multiple inheritance of CLASSES; interfaces give many types.
// Prefer an interface when you only need a capability (Comparable, Runnable).Common mistakes
The mistake is a deep inheritance chain made to reuse three lines of code, which becomes impossible to reason about by the fourth level. Copy the three lines, or move them into a helper. Reuse is not a reason to couple two classes for ever.
Worked example
A Print interface with one print() method lets three unrelated report classes be stored in one list and printed in a loop. An abstract base class would force them to share a family tree they do not have.
Your practice task
Write one interface, implement it in three classes, store them in a List<Print> and print all three through the interface.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
Inheritance extends a class: class SavingsAccount extends Account inherits the fields and methods and can override behaviour.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.