1. Introduction to Inheritance
1.1 What is Inheritance
Inheritance is a mechanism where one class acquires properties and methods of another class.
1.2 Why Use Inheritance
- Code reuse
- Reduces redundancy
- Improves maintainability
1.3 Real-World Example
- Parent → Animal
- Child → Dog
1.4 Syntax
class Parent {
// properties and methods
}class Child extends Parent {
// additional features
}
2. Types of Inheritance
2.1 Single Inheritance
One class inherits from one parent.
class A {}
class B extends A {}
2.2 Multilevel Inheritance
A chain of inheritance.
class A {}
class B extends A {}
class C extends B {}
2.3 Hierarchical Inheritance
Multiple classes inherit from one parent.
class A {}
class B extends A {}
class C extends A {}
2.4 Multiple Inheritance (Concept)
Java does not support multiple inheritance with classes.
2.5 Hybrid Inheritance
Combination of different types (not directly supported with classes).
3. Method Overriding
3.1 Definition
Method overriding allows a subclass to provide a specific implementation of a method already defined in the parent class.
3.2 Example
class Animal {
void sound() {
System.out.println("Animal sound");
}
}class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
3.3 Rules
- Same method name
- Same parameters
- Same return type
3.4 @Override Annotation
@Override
void sound() {
System.out.println("Dog barks");
}
3.5 Runtime Polymorphism
Method is decided at runtime based on object.
4. super Keyword
4.1 Definition
The super keyword refers to the parent class object.
4.2 Access Parent Variable
super.variableName;
4.3 Call Parent Method
super.methodName();
4.4 Call Parent Constructor
super();
4.5 Example
class Animal {
void show() {
System.out.println("Animal class");
}
}class Dog extends Animal {
void show() {
super.show();
System.out.println("Dog class");
}
}
5. final Keyword
5.1 Definition
The final keyword is used to restrict changes.
5.2 final Variable
final int MAX = 100;
5.3 final Method
final void display() {}
Cannot be overridden.
5.4 final Class
final class A {}
Cannot be extended.
5.5 Example
final class Animal {}class Dog extends Animal {} // Error
Conclusion
Inheritance is a powerful feature in Java that allows code reuse and better organization of programs. By understanding inheritance types, method overriding, and keywords like super and final, beginners can build efficient and scalable applications.
Leave a Reply