Inheritance in Java
• Understanding Object-Oriented
Principles through Code
• Presented by: Saurav Sharma
• Presented to : Shahid Sir
• Institution : Apex University
Introduction to
Inheritance
• • Inheritance is a key concept in OOP.
• • Allows one class (subclass) to inherit
fields and methods from another
(superclass).
• • Promotes code reusability and
hierarchical classification.
Why Use Inheritance?
• • Code Reusability: Avoids duplication.
• • Method Overriding: Allows subclass to
redefine methods.
• • Extensibility: Easily add new features
to existing code.
• • Polymorphism: Enables dynamic
method dispatch.
Syntax of Inheritance in
Java
• class SuperClass {
• // fields and methods
• }
• class SubClass extends SuperClass {
• // additional fields and methods
• }
• • Use of 'extends' keyword.
• • Subclass inherits all non-private members.
Types of Inheritance in
Java
• • Single Inheritance (supported)
• • Multilevel Inheritance (supported)
• • Hierarchical Inheritance (supported)
• • Multiple Inheritance using Interfaces
(not supported for classes)
Example – Single
Inheritance
• class Animal {
• void eat() {
• System.out.println("This animal eats food.");
• }
• }
• class Dog extends Animal {
• void bark() {
• System.out.println("The dog barks.");
• }
• }
• Output:
• This animal eats food.
• The dog barks.
Method Overriding
• class Animal {
• void sound() {
• System.out.println("Animal makes sound");
• }
• }
• class Dog extends Animal {
• void sound() {
• System.out.println("Dog barks");
• }
• }
super Keyword
• • Refers to superclass members.
• • Used to:
• - Access superclass constructor.
• - Call superclass methods.
• Example:
• super.sound();
Inheritance and
Constructors
• • Constructors are not inherited.
• • Subclass constructor implicitly or explicitly calls the superclass constructor.
• Example:
• class A {
• A() {
• System.out.println("A's constructor");
• }
• }
• class B extends A {
• B() {
• super(); // optional
• System.out.println("B's constructor");
• }
• }
Summary and Q&A
• • Inheritance is crucial for OOP in Java.
• • Enables modular, maintainable, and
scalable code.
• • Key concepts: extends, method
overriding, super, constructor chaining.
• Questions?