Q.Define inheritance. Write a Java program in which a class Student inherits from a class Person, reusing a field and a method of Person.
Definition. Inheritance is the mechanism by which one class — the child (subclass) — acquires the fields and methods of another class — the parent (superclass). The child gets the parent's members automatically and may add its own. It models an 'is-a' relationship: a Student is a Person. The keyword is extends.
Program:
class Person { // parent / superclass
String name;
void introduce() {
System.out.println("I am " + name);
}
}
class Student extends Person { // child inherits from Person
int rollNo; // Student's own field
void showRoll() {
System.out.println(name + " has roll " + rollNo); // 'name' reused
}
}
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(); // I am Amit (method inherited)
s.showRoll(); // Amit has roll 21
}
}
What is reused. Student never declares name or introduce(), yet the object s uses both — that is inheritance at work. Student also adds rollNo and showRoll() for its own needs, showing that a child can extend the parent.
Why it is useful. Common code (here, name and introduce) is written once in Person and shared by every class that extends it, avoiding duplication and keeping related classes organised.
Inheritance (via extends) lets Student reuse Person's name field and introduce() method while adding its own rollNo and showRoll(). The program prints 'I am Amit' and 'Amit has roll 21'.
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.