Inheritance
Inheritance is one of the core features of OOP, enabling code reuse.
What is Inheritance
Inheritance allows a subclass to inherit attributes and methods from a parent class, enabling code reuse.
Benefits of Inheritance
| Benefit | Description |
|---|---|
| Code reuse | No need to rewrite parent class code |
| Extensibility | Subclasses can add their own attributes and methods |
| Foundation for polymorphism | Inheritance is a prerequisite for polymorphism |
The extends Keyword
Syntax
JAVA
public class ChildClass extends ParentClass {
// Attributes and methods specific to the child class
}
Example: Inheritance
JAVA
// Parent class
public class Animal {
String name;
int age;
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class
public class Dog extends Animal {
String breed;
public void bark() {
System.out.println(name + " is barking");
}
}
public class Cat extends Animal {
String color;
public void meow() {
System.out.println(name + " is meowing");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "Buddy";
dog.age = 3;
dog.breed = "Golden Retriever";
dog.eat(); // Buddy is eating (inherited from Animal)
dog.sleep(); // Buddy is sleeping (inherited from Animal)
dog.bark(); // Buddy is barking (Dog's own method)
Cat cat = new Cat();
cat.name = "Whiskers";
cat.age = 2;
cat.color = "White";
cat.eat(); // Whiskers is eating
cat.meow(); // Whiskers is meowing
}
}
The super Keyword
super is a reference to the parent class.
Use 1: Call Parent Constructor
JAVA
public class Animal {
String name;
int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Dog extends Animal {
String breed;
public Dog(String name, int age, String breed) {
super(name, age); // Call parent constructor
this.breed = breed;
}
}
Use 2: Call Parent Method
JAVA
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
@Override
public void eat() {
super.eat(); // Call parent's eat
System.out.println("Dog is chewing a bone");
}
}
Example: Using super
JAVA
public class Person {
protected String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void showInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Student extends Person {
private double score;
public Student(String name, int age, double score) {
super(name, age); // Call parent constructor
this.score = score;
}
@Override
public void showInfo() {
super.showInfo(); // Call parent's showInfo
System.out.println("Score: " + score);
}
}
public class SuperDemo {
public static void main(String[] args) {
Student stu = new Student("Alice", 20, 95.5);
stu.showInfo();
// Name: Alice, Age: 20
// Score: 95.5
}
}
Method Overriding
Subclasses can override parent class methods to implement different behavior.
Overriding Rules
| Rule | Description |
|---|---|
| Same method name | Required |
| Same parameter list | Required |
| Same return type | Or a subclass of the parent's return type |
| Access cannot be more restrictive | Can be more permissive |
@Override Annotation
JAVA
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("Dog is chewing a bone");
}
}
💡 Recommendation: Always add the
@Override annotation when overriding methods. The compiler will verify the override is correct.
The Object Class
All classes directly or indirectly inherit from the Object class.
Common Object Methods
| Method | Description |
|---|---|
toString() |
Returns a string representation of the object |
equals() |
Compares objects for equality |
hashCode() |
Returns the object's hash code |
getClass() |
Returns the object's class information |
Overriding toString()
JAVA
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
public static void main(String[] args) {
Student stu = new Student("Alice", 20);
System.out.println(stu); // Automatically calls toString()
// Output: Student{name='Alice', age=20}
}
}
Overriding equals()
JAVA
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student other = (Student) obj;
return age == other.age && name.equals(other.name);
}
@Override
public int hashCode() {
return name.hashCode() * 31 + age;
}
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
Student s2 = new Student("Alice", 20);
System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)
}
}
instanceof
The instanceof operator checks if an object is an instance of a particular class.
JAVA
public class InstanceofDemo {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog instanceof Dog); // true
System.out.println(dog instanceof Animal); // true
System.out.println(dog instanceof Object); // true
}
}
Inheritance Notes
| Note | Description |
|---|---|
| Single inheritance | Java only supports single inheritance |
| Cannot inherit private | Private members cannot be inherited |
| Cannot inherit constructors | Constructors cannot be inherited |
| Object is root class | All classes inherit from Object |
❓ Frequently Asked Questions
Q Why doesn't Java support multiple inheritance?
A To avoid the diamond problem (ambiguity when multiple parents have the same method). Java uses interfaces for similar functionality.
Q When should I use inheritance?
A When two classes have an "is-a" relationship, like Dog is a Animal.
Q How do I choose between inheritance and composition?
A Prefer composition (has-a relationship). Inheritance increases coupling.
📖 Summary
- Inheritance uses the extends keyword for code reuse
- super is used to call parent constructors and methods
- Method overriding: subclasses replace parent class methods
- All classes inherit from the Object class
- instanceof checks object type
📝 Exercises
- Shape hierarchy: Define a Shape parent class with Circle and Rectangle subclasses, calculate areas
- Employee hierarchy: Define an Employee parent class with Manager and Developer subclasses
- toString/equals: Override toString and equals methods in a Student class
Next Lesson
In the next lesson, we'll learn about Polymorphism and Abstraction — core OOP features.



