Why inheritance?
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Inheritance lets a new class get the fields and methods of an existing class. You write the common code once in a parent class, and each child class gets it for free and adds its own extra parts.
The same fields, again and again
Inheritance is the mechanism by which one class (the child) acquires the fields and methods of another class (the parent) using the extends keyword. It lets common code be written once and reused.
A school app needs a Student class and a Teacher class. Both have a name, an age and a method to show them, so without inheritance you type all of it twice.
Example 1 · Student and Teacher without inheritance
class Student { String name; int age; int marks;
void showBasic() { System.out.println(name + ", age " + age); }}
class Teacher { String name; int age; String subject;
void showBasic() { System.out.println(name + ", age " + age); }}
public class RepeatDemo { public static void main(String[] args) { Student s = new Student(); s.name = "Aarav"; s.age = 17; Teacher t = new Teacher(); t.name = "Mrs. Iyer"; t.age = 42; s.showBasic(); t.showBasic(); }}Aarav, age 17 Mrs. Iyer, age 42
What this code does
- The program works, but
name,ageandshowBasic()are typed twice. - To change how the details are shown, you must edit both classes. This copying is what inheritance removes.
Copied code is hard to keep right. If the way you show a name changes, you must edit every class; miss one, and the app shows two styles. Add Driver and Clerk, and the same lines appear four times.
Write it once in a parent class
The superclass (parent class or base class) is the class whose fields and methods are inherited. The subclass (child class or derived class) is the class that inherits them using extends.
Put the common fields and methods in one class, Person, and write class Student extends Person. Now Person is the parent and Student the child: Student gets everything Person has and adds only its own parts, like marks.
Example 2 · The same program with a Person parent
class Person { String name; int age;
void showBasic() { System.out.println(name + ", age " + age); }}
class Student extends Person { int marks;}
class Teacher extends Person { String subject;}
public class ParentDemo { public static void main(String[] args) { Student s = new Student(); s.name = "Aarav"; s.age = 17; s.marks = 91; Teacher t = new Teacher(); t.name = "Mrs. Iyer"; t.subject = "Physics"; s.showBasic(); System.out.println("Marks: " + s.marks); System.out.println(t.name + " teaches " + t.subject); }}Aarav, age 17 Marks: 91 Mrs. Iyer teaches Physics
What this code does
name,ageandshowBasic()are written once, inPerson.StudentandTeacherget them throughextends Person.- Each child adds only what is new:
marksfor a student,subjectfor a teacher.
Example 3 · A child adds its own method
class Person { String name;
void greet() { System.out.println("Hello, I am " + name); }}
class Student extends Person { int marks;
void showResult() { System.out.println(name + " scored " + marks); }}
public class ChildMethodDemo { public static void main(String[] args) { Student s = new Student(); s.name = "Kavya"; s.marks = 88; s.greet(); s.showResult(); }}Hello, I am Kavya Kavya scored 88
What this code does
- A
Studentobject can callgreet()from the parent andshowResult()from its own class. - Inside
showResult(), the child uses the inherited fieldnamedirectly, as if it were its own.
The class you build on is the parent class, also called the superclass or base class. The new class is the child class, also called the subclass or derived class. All three names mean the same thing.
The gain is real: the common code is written once, a fix in Person reaches every child, and the code itself says that a student and a teacher are both people.
The IS-A test, one way only
The IS-A relationship is the link between a child class and its parent: every child object is also a kind of parent object, as in "a Student is a Person". Use inheritance only when this sentence is true.
Before you write extends, say the sentence "a child is a parent". "A Student is a Person" is true, so inheritance fits. This is the IS-A relationship, and it works in one direction only.
Example 4 · Mistake: a parent object calls a child method
class Person { String name;
void greet() { System.out.println("Hello, I am " + name); }}
class Student extends Person { int marks;
void showResult() { System.out.println(name + " scored " + marks); }}
public class OneWayDemo { public static void main(String[] args) { Person p = new Person(); p.name = "Rohan"; p.greet(); p.showResult(); }}OneWayDemo.java:22: error: cannot find symbol
p.showResult();
^
symbol: method showResult()
location: variable p of type Person
1 errorWhat this code does
showResult()is inStudent, not inPerson. A plainPersonobject does not have it.- Inheritance goes one way: the child gets the parent's members, never the other way round.
A Student is a Person, but a Person is not always a Student. So a child can use everything the parent has, while a plain parent object knows nothing about the child's extra members.
Student objects each have their own name, even though the field is written in Person.When not to use inheritance
The HAS-A relationship means one object owns another object as a field, as in "a Car has an Engine". It is written with a field, not with extends.
A Car class wants the start() method of an Engine class. Do not write extends just to borrow a method: "a Car is an Engine" is false, even though Java compiles it.
Example 5 · It compiles, but fails the IS-A test
class Engine { int horsePower;
void start() { System.out.println("Engine started: " + horsePower + " hp"); }}
class Car extends Engine { String model;}
public class WrongIsADemo { public static void main(String[] args) { Car c = new Car(); c.model = "Nexon"; c.horsePower = 118; c.start(); }}Engine started: 118 hp
What this code does
- Java compiles this, because it does not check whether your design makes sense. You must do the IS-A test yourself.
- "A Car is an Engine" is false, yet
Carnow hashorsePowerandstart()as if it were one. Every change toEnginenow changesCartoo.
Example 6 · The fix: a car has an engine
class Engine { int horsePower;
void start() { System.out.println("Engine started: " + horsePower + " hp"); }}
class Car { String model; Engine engine = new Engine();
void drive() { engine.start(); System.out.println(model + " is moving"); }}
public class HasADemo { public static void main(String[] args) { Car c = new Car(); c.model = "Nexon"; c.engine.horsePower = 118; c.drive(); }}Engine started: 118 hp Nexon is moving
What this code does
Carholds anEngineobject in a field, so a car has an engine instead of being one.drive()asks its engine to start.Caruses the engine's work without pretending to be an engine, and it has noextendsat all.
A car has an engine. That is a HAS-A relationship, and the engine belongs in a field inside Car, as in Example 6. HAS-A vs IS-A (opens in a new tab) covers this way of building classes.
A quick rule: if "child is a parent" sounds silly when you say it aloud, do not use inheritance.
Next step
Check your understanding
11 quick questions