UNIT 3a - Inheritance

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 64

Inheritance in Java: Introduction,

Purpose, and Benefits


This presentation explores inheritance, a fundamental concept in object-oriented programming (OOP) in Java. Learn
about its purpose, benefits, and different types.
Introduction to Inheritance in Java
Inheritance in Java is a powerful mechanism that allows a class to inherit properties and methods from another
class. The class inheriting is called the subclass (child class), and the class being inherited from is called the
superclass (parent class).

Superclass (Parent Class) Subclass (Child Class)


The class that is being inherited from. The class that inherits from the superclass.
Purpose of Inheritance in Java
Inheritance serves multiple purposes, promoting code reusability, enabling method overriding, and facilitating
abstraction.

1 Code Reusability 2 Method Overriding 3 Abstraction


Developers can reuse Subclasses can provide their Abstract classes can be
existing code from the specific implementation of a created to define common
superclass, reducing method already defined in behaviors, which can be
redundancy and effort. the superclass, enabling inherited by multiple
runtime polymorphism. subclasses, promoting code
organization.
Benefits of Inheritance in Java
Inheritance brings several benefits to Java development, including improved code maintainability, enhanced
readability, and increased flexibility.

Improved Code Maintenance Enhanced Readability Flexibility

Inheritance organizes code in a New features can be easily added


Changes in the superclass hierarchical manner, making it through subclasses without
automatically propagate to easier to read and understand modifying existing code in the
subclasses, reducing the effort the relationships between superclass, increasing flexibility
required to maintain code. classes. and adaptability.
Types of Inheritance in Java
Java supports various types of inheritance, each with its own structure and characteristics.

1 Single Inheritance
A subclass inherits properties and methods from a single superclass.

2 Multilevel Inheritance
A subclass inherits from another subclass, forming a chain of inheritance.

3 Hierarchical Inheritance
Multiple subclasses inherit from a single superclass.

4 Hybrid Inheritance
A combination of two or more types of inheritance, achieved through interfaces in Java.
Single Inheritance
Single inheritance is the most basic form of inheritance in Java. A subclass inherits directly from one superclass.

Superclass Subclass

Animal Dog

Vehicle Car
Multilevel Inheritance
Multilevel inheritance involves a chain of inheritance where a subclass inherits from another subclass, which itself
inherits from a superclass.

Superclass
Animal

Subclass
Mammal

Sub-Subclass
Dog
Hierarchical Inheritance
Hierarchical inheritance allows multiple subclasses to inherit from a single superclass.

Animal
The superclass.

Dog
One subclass.

Cat
Another subclass.

Bird
Single Inheritance in Java
Inheritance is a fundamental concept in object-oriented programming. It allows you to create new classes based on existing
classes, inheriting their properties and behaviors. This promotes code reuse, hierarchical classification, and polymorphism,
making your code more efficient, organized, and flexible.

by dennis ebenezer
Introduction to Inheritance
1 What is Inheritance? 2 Why Use Inheritance?
Inheritance is a powerful mechanism in Java that Inheritance offers several advantages: it promotes
enables you to create new classes (subclasses) based code reusability by allowing you to reuse existing
on existing classes (superclasses). It establishes an code in new classes, creates a hierarchical
"is-a" relationship between classes, where the classification structure for organizing your classes,
subclass inherits properties and methods from the and enables polymorphism, allowing objects of
superclass. different types to be treated as if they were of the
same type.
Single Inheritance in Java
Definition Syntax

In Java, single inheritance allows a subclass to inherit from The syntax for single inheritance in Java is simple: you use
only one superclass. This ensures a clear and the keyword "extends" followed by the superclass name
straightforward inheritance hierarchy. A subclass can inherit within the subclass declaration. For example, "class Dog
all the public and protected members of the superclass, extends Animal { ... }" defines a "Dog" class that inherits
including fields and methods. from the "Animal" class.
Members Inheritance
Access Modifier Field Inheritance Method Inheritance Constructor Inheritance

public Inherited Inherited Not Inherited

protected Inherited Inherited Not Inherited

default Inherited (same package) Inherited (same package) Not Inherited

private Not Inherited Not Inherited Not Inherited


Method Overriding
Concept
Method overriding allows a subclass to provide a specific implementation for a method inherited from its superclass.
This is useful when the subclass requires a different behavior for the inherited method.

Use @Override
The @Override annotation is used to explicitly indicate that a method is overriding a method from the superclass.
This improves code readability and helps the compiler detect potential errors.

Example
For example, a "Dog" class might override the "speak()" method inherited from the "Animal" class to print "Woof!"
instead of the generic "Animal sounds." This allows the "Dog" class to have its own unique behavior.
Super Keyword
Purpose Syntax
The "super" keyword is used to refer to members of the The "super" keyword can be used to access fields,
superclass from within a subclass. This is necessary methods, and constructors of the superclass. For
when you need to access a superclass member that is example, "super.field" refers to the field named "field"
hidden by a member with the same name in the subclass in the superclass, "super.method()" calls the method
or when you want to call a superclass constructor. named "method" in the superclass, and "super()" calls
the superclass constructor.
Inheritance and Constructors

Constructor Chaining Example


When a subclass constructor is invoked, Java implicitly calls For example, if the "Dog" class has a constructor that takes
the no-argument constructor of its superclass. This is known the breed as an argument, it might call the superclass
as constructor chaining. If the superclass doesn't have a no- constructor with the "name" argument to initialize the
argument constructor, you need to explicitly call a specific "name" field of the "Animal" class.
superclass constructor using the "super()" keyword.
Inheritance and Polymorphism
1 Runtime Polymorphism
Runtime polymorphism is a fundamental concept in object-oriented programming that allows objects of different
types to be treated as if they were of the same type. This is achieved through method overriding and method binding.

2 Method Overriding
When a subclass overrides a method inherited from its superclass, it provides a specific implementation of that
method. This allows objects of different types to respond differently to the same method call.

3 Method Binding
Method binding is the process of associating a method call with the correct method implementation at runtime.
During runtime, the actual type of the object is determined, and the appropriate method implementation is called.
Multiple Inheritance using Interface in
Java

This presentation will delve into the concept of multiple inheritance in Java using interfaces. We will explore the challenges of multiple
inheritance with classes and how interfaces provide a powerful solution.
Multiple Inheritance: Challenges
Diamond Problem Method Ambiguity

Occurs when a subclass inherits from multiple classes that When a subclass inherits multiple methods with the same name
share a common ancestor, leading to ambiguity regarding but different implementations from different parent classes,
which implementation to use for methods inherited from the confusion arises about which method to invoke.
shared ancestor.
Java's Approach to Multiple Inheritance
No Multiple Inheritance
To avoid the complications of the diamond problem and method
ambiguity, Java does not support direct multiple inheritance with
classes.

Interface Solution
Java provides interfaces as a mechanism to achieve multiple inheritance
without the complexities of direct multiple inheritance.
What is an Interface?
1 Reference Type 2
Abstract Methods 3 Static Constants
An interface is a Interfaces define Interfaces can
reference type in methods that are also contain
Java, similar to a declared but not static constants,
class, but with a implemented. which are
different purpose These methods values that are
and structure. are abstract and shared by all
Interfaces cannot must be implementations
have concrete implemented by of the interface.
implementations classes that
for methods. implement the
interface.
Syntax of Interface
interface InterfaceName { // abstract methods }

Implementing Multiple
Interfaces
class ClassName implements Interface1, Interface2 {
// implementation of abstract methods }
Advantages of Interfaces
Code Reusability Interfaces promote code
reusability by allowing multiple
classes to implement the same
interface, sharing the same set of
methods.

Multiple Inheritance Interfaces provide a mechanism to


achieve multiple inheritance,
enabling classes to inherit
behavior from multiple sources
without the complexities of direct
multiple inheritance.
Flexibility and Scalability Interfaces enhance flexibility and
scalability by allowing classes to
be adapted to different situations
without modifying their core
functionality.
interface Dog {
void bark();
}
interface Cat {
void meow();
}
class Animal implements Dog, Cat {
public void bark() {
System.out.println("Dog is barking");
}
public void meow() {
System.out.println("Cat is meowing");
}
}
class Main {
public static void main(String args[]) {
Animal a = new Animal();
a.bark();
a.meow();
}
}
Dog is barking
Cat is meowing
interface A {
void display();
}

interface B {
void display();
}

class C implements A, B {
@Override
public void display() {
System.out.println("This is the display method from class C");
}
}

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.display();
}
}
This is the display method from class C
interface A {
default void display() {
System.out.println("Display method from interface A");
}
}

interface B {
default void display() {
System.out.println("Display method from interface B");
}
}

class C implements A, B {
@Override
public void display() {
A.super.display();
B.super.display();
System.out.println("This is the display method from class C");
}
}

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.display();
}
}
Display method from interface A
Display method from interface B
This is the display method from class C
Multilevel Inheritance: A Deeper Dive
Welcome to our exploration of multilevel inheritance, a powerful concept in
object-oriented programming. This presentation will unravel the intricacies of
this inheritance model, providing a comprehensive understanding of its
structure, benefits, and potential drawbacks. Prepare to delve into the realm of
class hierarchies and inheritance chains as we demystify this fundamental
programming concept.
What is Multilevel Inheritance?

In object-oriented programming, multilevel inheritance allows for a hierarchical structure where classes inherit from other
classes, forming a chain-like relationship. Think of it as a family tree, where a child inherits traits from their parent, and the
parent, in turn, inherited traits from their own parent. This hierarchical inheritance enables code reuse, polymorphism, and a
structured way to organize your code.

For example, consider a scenario where you have a base class "Animal" with attributes like "name" and "age." A derived
class "Mammal" inherits these attributes and adds its own specific characteristics like "hasFur" and "givesBirth." Finally, a
class "Dog" inherits all the features of "Mammal" and adds "breed" and "bark" to its repertoire. This demonstrates how
multilevel inheritance helps you organize related classes in a logical manner.
Multilevel Inheritance Structure: A Visual
Representation
Imagine a hierarchical chain of classes where features flow downwards. This is the essence of multilevel inheritance, where a class
inherits from another class, which in turn inherits from a base class.

Base Class: Class A Intermediate Class: Class B Derived Class: Class C

The foundation of the inheritance Inherits all features from Class A and Inherits features from both Class B and
chain. This class defines the core adds its own specialized features. It Class A. This class builds upon the
features that will be passed down to acts as a bridge between the base and existing functionality of its parent
subsequent classes. the derived class. classes, creating a highly specialized
class.

This chain-like structure enables a well-organized inheritance hierarchy, ensuring that related classes share common features and
functionalities. The key to understanding this structure is that each derived class inherits the features of its immediate parent, as well
as all features inherited by its parent's parent.
class A {
void displayA() {
System.out.println("Class A");
}
}
class B extends A {
void displayB() {
System.out.println("Class B");
}
}
class C extends B {
void displayC() {
System.out.println("Class C");
}
}
public class Test {
public static void main(String[] args) {
C obj = new C();
obj.displayA();
obj.displayB();
obj.displayC();
}
}
Output:

Class A
Class B
Class C
Understanding Constructor Execution Order
In multilevel inheritance, when you create an object of the derived class, the
constructors of all parent classes are executed in a specific order, ensuring that
the necessary initialization happens before the derived class constructor is
called. This order is essential for maintaining the integrity of the object and its
inherited attributes.
class A {
A() {
System.out.println("A's constructor");
}
}

class B extends A {
B() {
System.out.println("B's constructor");
}
}

class C extends B {
C() {
System.out.println("C's constructor");
}
}

public class Main {


public static void main(String[] args) {
C obj = new C();
}
}
When you create an object of class C, "C obj = new C();", the output will be:

A's constructor
B's constructor
C's constructor

This order ensures that the base class (A) is initialized first,
followed by the intermediate class (B), and finally the derived
class (C). This orderly construction guarantees that all necessary
attributes and methods are properly set up before the object is
fully created.
Method Overriding in Multilevel Inheritance
Method overriding in multilevel inheritance is a concept in object-oriented
programming where a method in a subclass (child class) replaces a method
inherited from its superclass (parent class) with a new implementation. In
multilevel inheritance, this concept extends across multiple levels of the class
hierarchy. Here's an explanation with examples:
Understanding Multilevel Inheritance
Multilevel inheritance is a type of inheritance where a class is derived from
another class, which is also derived from another class. For example, if class C
inherits from class B, and class B inherits from class A, this is multilevel
inheritance:
class A {
void display() {
System.out.println("Class A display method");
}
}

class B extends A {
@Override
void display() {
System.out.println("Class B display method");
}
}

class C extends B {
@Override
void display() {
System.out.println("Class C display method");
}
}

public class TestInheritance {


public static void main(String[] args) {
C obj = new C();
obj.display(); // Output: Class C display method

B objB = new B();


objB.display(); // Output: Class B display method

A objA = new A();


objA.display(); // Output: Class A display method
}
}
Explanation:
1.Class A has a method display() which prints "Class A display method".
2.Class B extends Class A and overrides the display() method to print "Class B display method".
3.Class C extends Class B and overrides the display() method to print "Class C display method".
When you create an object of Class C and call the display() method,
it will invoke the overridden method in Class C,
demonstrating method overriding in a multilevel inheritance scenario.
Output:

Class C display method


Class B display method
Class A display method
Advantages of Multilevel Inheritance: Embracing Reusability

Multilevel inheritance offers several advantages for developers, making it a valuable tool for efficient and organized code development.

1 Code Reusability
One of the most significant benefits is code reusability. By inheriting from parent classes, you eliminate the need to rewrite the same code for each derived
class. This not only saves development time but also reduces the likelihood of errors.

2 Method Overriding
Multilevel inheritance allows you to override methods from parent classes. This enables you to customize the behavior of inherited methods in each
derived class, creating a more flexible and adaptable codebase.

3 Organized Code Structure


Multilevel inheritance helps to organize your code into logical groups. It facilitates the creation of hierarchies where related classes inherit from
common base classes. This structure improves code readability and maintainability.

These advantages demonstrate how multilevel inheritance can contribute to developing efficient, maintainable,
and reusable code.
Disadvantages of Multilevel Inheritance: Exploring Potential Drawbacks

While multilevel inheritance offers valuable advantages, it's crucial to be aware of potential disadvantages that might arise in complex scenarios.

Increased Complexity
Tight Coupling
As the number of inheritance levels increases, the code can Multilevel inheritance creates tight coupling between
become more complex and harder to understand. classes. Changes in parent classes can potentially affect all
Debugging and maintaining such a hierarchical structure derived classes, leading to cascading changes and
can be challenging, especially with multiple layers of increased maintenance effort.
dependencies.

While these disadvantages might seem daunting, they can be mitigated with careful planning and
adherence to best practices. Understanding the potential drawbacks can help you make informed
decisions about whether multilevel inheritance is the appropriate solution for your project.
Real-World Examples: Putting Multilevel Inheritance into Practice

Multilevel inheritance is a fundamental concept with numerous real-world applications in software development. Let's explore a few
examples to solidify our understanding.

Imagine a scenario where you're developing a software application for managing a zoo. You might have a base class
"Animal" with attributes like "name", "age", and "habitat." From this base class, you could derive "Mammal", "Bird", and
"Reptile." These classes would inherit the base attributes and add their own specific characteristics. Further, you could
derive classes like "Lion", "Eagle", and "Crocodile" from their respective parent classes, inheriting features from both the
base class and the intermediate class. This example demonstrates how multilevel inheritance can help you model complex
relationships and create highly specialized classes.

In essence, multilevel inheritance provides a structured and efficient way to represent real-world
hierarchies in your code, ensuring reusability, polymorphism, and a clear organization of your classes.
Hierarchical Inheritance: A
Fundamental Concept
In the world of object-oriented programming, inheritance is a powerful tool that allows us to create relationships between classes.
Hierarchical inheritance, a specific type of inheritance, is a fundamental concept that plays a crucial role in structuring and organizing
code. This presentation will delve into the depths of hierarchical inheritance, exploring its definition, real-world applications, and the
advantages and disadvantages it presents.
Hierarchical Inheritance: The Core Idea
Hierarchical inheritance is characterized by a tree-like structure where a single base class, referred to as the parent class, acts as the foundation
for multiple derived classes, known as child classes. This structure mimics real-world hierarchical relationships. For instance, consider a
Vehicle class, representing the parent class. From this class, we can derive subclasses such as Car, Bike, and Truck, each inheriting properties
and behaviors from the Vehicle class. This hierarchical organization simplifies code and promotes reusability.

1 Parent Class
The parent class is the foundation of the hierarchy, containing common attributes and methods shared by its descendants.

2 Child Classes
Child classes inherit properties and methods from the parent class, extending and specializing them to meet their specific
requirements.

3 Inheritance Relationship
The "is-a" relationship signifies inheritance: a Car "is a" Vehicle, a Bike "is a" Vehicle, and a Truck "is a" Vehicle.
Hierarchical Inheritance in Action
Let's visualize hierarchical inheritance with a real-world example. Imagine we are designing a program to manage a fleet of vehicles. We can
create a base class called Vehicle with attributes like make, model, and year. Then, we can derive subclasses like Car, Bike, and Truck, each
inheriting the basic properties of a Vehicle and adding specific attributes, like the number of doors for a Car or the load capacity for a Truck.
This hierarchical structure allows us to reuse code and avoid redundant implementations.

Vehicle Class Car Class Bike Class

Common attributes: make, model, year Inherited attributes: make, model, year Inherited attributes: make, model, year

Common methods: start(), stop(), Specific attribute: number of doors Specific attributes: number of gears, type
accelerate() (mountain, road)
Specific methods: honk(), openTrunk()
Specific method: ringBell()
Overriding Methods: Adapting to Subclass Needs

In hierarchical inheritance, subclasses can override methods inherited from the base class. This mechanism allows subclasses to provide
their own, more specialized implementations for methods that are shared by the parent class. For example, the Vehicle class might have a
generic "start()" method. However, the Car subclass could override this method to include specific actions, such as turning on the headlights
or adjusting the seat position.

Vehicle Class
start() method: basic engine ignition

Car Class
override start() method: headlights, seat adjustment, engine ignition
Method Overloading: Flexibility in Method
Signatures
While method overriding involves changing the implementation of an inherited method, method overloading deals with having
multiple methods with the same name but different parameter lists within a single class. This allows for greater flexibility and
adaptability in how objects interact with each other. For instance, a Vehicle class could have multiple "move()" methods with different
parameters to represent different ways of moving, such as "move(speed)" for constant speed movement or "move(distance, direction)"
for directional movement.

Method Overloading Method Overriding


Multiple methods with the same name but different Subclass provides a specialized implementation for a
parameter lists within a single class. method inherited from the parent class.
The Advantages of Hierarchical Inheritance
Hierarchical inheritance offers numerous advantages for software developers. First and foremost, it promotes code reusability. Instead
of writing the same code repeatedly in different subclasses, we can simply inherit from the base class, ensuring that common
functionality is shared across the hierarchy. This reduces redundancy and promotes code consistency.

1 Code Reusability 2 Polymorphism 3 Hierarchical


Classification
Reusing code from parent Treating objects of different
classes, reducing redundancy and subclasses as objects of the base Modeling real-world
enhancing consistency. class, enabling flexible code relationships effectively,
design. improving code organization and
readability.
Navigating the Challenges of Hierarchical
Inheritance
While hierarchical inheritance brings many benefits, it's crucial to be aware of its potential drawbacks. One challenge is tight coupling,
meaning that subclasses become heavily dependent on the base class. Changes to the base class can have cascading effects on all its
subclasses, potentially leading to unexpected errors. Furthermore, excessive inheritance, often referred to as "inheritance hell," can
result in complex and difficult-to-maintain code.

Advantages Disadvantages

Code reusability Tight coupling

Polymorphism Inheritance hell

Hierarchical classification Complexity


class A {
public void methodA() {
System.out.println("method of Class A");
}
}
class B extends A {
public void methodB() {
System.out.println("method of Class B");
}
}
class C extends A {
public void methodC() {
System.out.println("method of Class C");
}
}
class D extends A {
public void methodD() {
System.out.println("method of Class D");
}
}
class JavaExample {
public static void main(String args[]) {
B obj1 = new B();
C obj2 = new C();
D obj3 = new D(); //All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
Output:

method of Class A
method of Class A
method of Class A
Best Practices for Hierarchical Inheritance
To mitigate the potential challenges of hierarchical inheritance, it's important to follow some best practices. Keep your inheritance
hierarchies shallow and well-defined. Avoid excessive inheritance levels as it can lead to complexity. Use interfaces to promote
flexibility and reduce tight coupling. Design your classes with clear responsibilities, adhering to the Single Responsibility Principle
(SRP). And lastly, document your code thoroughly to make it understandable for others and for your future self.

Document Your Code Follow Best Practices Design with Clarity


Thorough documentation ensures that Adhering to best practices helps ensure Clearly defined responsibilities for each
your code is easy to understand for code maintainability and readability. class contribute to a maintainable and
others and your future self. well-organized codebase.
Hybrid Inheritance in Java
Hybrid inheritance combines multiple inheritance types, offering greater flexibility in modeling complex relationships in Java. While
Java doesn't directly support multiple inheritance with classes, it can be achieved through a combination of interfaces and classes,
simulating this complex inheritance pattern.
Understanding Hybrid Inheritance
1 2 3

Base Interface Specialized Interfaces Implementing Classes


A base interface (e.g., Shape) Specialized interfaces (e.g., Classes (e.g., Circle, Rectangle,
defines fundamental attributes or TwoDimensionalShape, ColoredCircle) implement one or
methods common to all inheriting ColoredShape) extend the base more interfaces, inheriting their
classes. interface, adding specific features. methods and characteristics.
Simulating Multiple Inheritance with Interfaces

Interface Inheritance Class Implementation

Interfaces can extend other interfaces, forming a hierarchy. Classes can implement multiple interfaces, inheriting their
This allows for multiple inheritance through interface methods and attributes. This simulates multiple inheritance
implementation. with classes.
An Example: Combining Shapes and Color
1 Shape Interface 2 TwoDimensionalShape 3 ColoredShape Interface
Interface
A basic Shape interface defines
common properties like area or Extends Shape, adding methods Extends Shape, adding methods
perimeter calculation. specific to 2D shapes (e.g., related to color (e.g., getColor,
getArea, getPerimeter). setColor).

4 ColoredCircle Class
Implements both Circle and ColoredShape, inheriting attributes and methods from both interfaces.
class Parents
{
public void displayParents()
{
System.out.println("Two Parents");
}
}
interface Mother
{
public void show();
}
interface Father
{
public void show();
}
public class Child extends Parents implements Mother, Father
{
public void show()
{
System.out.println("Mother and Father are parents ");
}
public void displayChild()
{
System.out.println("Mother and Father have one child");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
Output:
Implementation of Hybrid Inheritance in Java
Mother and Father are parents
Mother and Father have one child
Advantages of Hybrid Inheritance
Flexibility Code Reusability
Hybrid inheritance enables modeling diverse real-world Sharing code across classes and interfaces through
scenarios through a combination of inheritance types. inheritance reduces redundancy and promotes consistency.
Challenges and Considerations
Complexity
Hybrid inheritance can lead to intricate class hierarchies that might be difficult to maintain or understand.

Potential for Issues


While less severe than with multiple inheritance with classes, hybrid inheritance can still result in diamond problem-like
situations.

Careful Design
Thorough planning and careful design are crucial to avoid unintended conflicts and maintain code clarity.
Best Practices for Implementing Hybrid
Inheritance
Use interfaces judiciously to achieve the desired inheritance behavior.

Consider alternative design patterns like composition if complexity becomes overwhelming.

Thoroughly test your code to identify potential issues related to interface conflicts or method overrides.
Real-World Applications

Vehicle Systems Building Design Game Development


Modeling vehicles with different types Representing buildings with different Creating characters with various abilities
of engines (e.g., electric, gas) and structural components (e.g., concrete, (e.g., jumping, shooting) and visual
features (e.g., sunroof, GPS). steel) and functionalities (e.g., elevators, effects (e.g., glowing, shadow).
heating).

You might also like