Inheritance in Java
Understanding Code Reusability in
Object-Oriented Programming
By Sinu Chhillar
Introduction to Inheritance
• Inheritance is a mechanism where one class
acquires the properties and behaviors of
another class.
• Purpose:
• - Code reusability
• - Better organization
• - Maintainability
Why Use Inheritance?
• - Avoids code duplication
• - Enhances code maintainability
• - Establishes relationships between classes (IS-
A relationship)
• - Enables method overriding for
polymorphism
Types of Inheritance in Java
• 1. Single Inheritance
• 2. Multilevel Inheritance
• 3. Hierarchical Inheritance
• 4. Hybrid Inheritance (Not directly supported
in Java)
• 5. Multiple Inheritance (Through Interfaces)
Syntax of Inheritance
• class Parent {
• void display() { System.out.println("This is
the Parent class"); }
• }
• class Child extends Parent {
• void show() { System.out.println("This is the
Child class"); }
• }
Method Overriding in Inheritance
• class Animal {
• void sound() { System.out.println("Animal
makes a sound"); }
• }
• class Dog extends Animal {
• void sound() { System.out.println("Dog
barks"); }
• }
The 'super' Keyword
• Used to refer to the immediate parent class.
• Example:
• class Parent {
• void message()
{ System.out.println("Message from Parent"); }
• }
• class Child extends Parent {
Abstract Classes and Interfaces
• Abstract classes can have both abstract and
non-abstract methods.
• Interfaces allow multiple inheritance.
• Example:
• interface A { void methodA(); }
• interface B { void methodB(); }
• class C implements A, B { public void
Conclusion
• - Inheritance allows code reuse and improves
structure.
• - Helps implement polymorphism.
• - Important for designing scalable applications.
Q&A - Any Questions?