Information Technology · Ch 2 — Programming
Inheritance
Inheritance
Inheritance lets one class reuse the fields and methods of another class instead of rewriting them. The class we inherit from is the parent (also called superclass or base class); the class that inherits is the child (also called subclass or derived class). The child automatically gets the parent's members and can add its own.
The keyword for inheritance in Java is extends.
class Person { // parent / superclass
String name;
void introduce() {
System.out.println("I am " + name);
}
}
class Student extends Person { // child inherits from Person
int rollNo; // adds its own field
void showRoll() {
System.out.println(name + " has roll " + rollNo); // 'name' is inherited
}
}
public class Demo {
public static void main(String[] args) {
Student s = new Student();
s.name = "Amit"; // field inherited from Person
s.rollNo = 21; // field of Student
s.introduce(); // method inherited from Person
s.showRoll();
}
}
Student never declares name or introduce(), yet it can use them — that is inheritance. It expresses an "is-a" relationship: a Student is a Person.
Why inheritance is useful
- Reuse: common code is written once in the parent and shared by every child.
- Extension: a child can add new fields and methods for its special needs.
- Organisation: related classes form a clear hierarchy that mirrors the real world.
Method overriding and super
A child may override a parent's method — redefine it with the same name and parameters — to give its own version:
class Person {
void introduce() { System.out.println("I am a person"); }
}
class Student extends Person {
void introduce() { // overrides the parent's version
super.introduce(); // call the parent's method too
System.out.println("...and a student");
}
}
The keyword super refers to the parent, so super.introduce() runs the parent's version before the child adds its line. Overriding lets each child behave differently while sharing the same method name — a key idea behind polymorphism.
Types of inheritance
- Single — one child from one parent (
B extends A). - Multilevel — a chain (
C extends B extends A); C inherits from both. - Hierarchical — several children from one parent (
B extends A,C extends A). …
A mechanism by which one class (the child/subclass) acquires the fields and methods of another class (the parent/superclass), expressing …
The Java keyword that makes one class inherit from another, e.g. `class Student e …
The superclass (parent) is inherited from; the subclass (child) inherits its members and may add or …
Redefining an inherited method in the child class with the same name and parameters to give a di …
A keyword referring to the parent class, used to call the parent's constructor or overridden meth …