UNIT 3a - Inheritance
UNIT 3a - Inheritance
UNIT 3a - Inheritance
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
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
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.
interface B {
void display();
}
class C implements A, B {
@Override
public void display() {
System.out.println("This is the display method from class C");
}
}
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");
}
}
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.
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");
}
}
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");
}
}
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.
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.
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.
Advantages Disadvantages
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.
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.
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.
Thoroughly test your code to identify potential issues related to interface conflicts or method overrides.
Real-World Applications