0% found this document useful (0 votes)
67 views

Java Week - 8

Inheritance in Java allows child classes to inherit properties and behaviors from parent classes. There are several types of inheritance in Java including single, multilevel, hierarchical, and hybrid inheritance. The key aspects are: 1) Single inheritance allows a child class to inherit from one parent class. 2) Multilevel inheritance allows a child class to inherit from another child class. 3) Hierarchical inheritance allows one parent class to have multiple child classes. 4) Hybrid inheritance combines two or more inheritance types through combinations like single/multilevel or hierarchical/single inheritance. 5) Multiple inheritance is not supported in Java to avoid complexity and ambiguity. The Open Closed Principle in SOLID

Uploaded by

Sheshgiri Sheshu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Java Week - 8

Inheritance in Java allows child classes to inherit properties and behaviors from parent classes. There are several types of inheritance in Java including single, multilevel, hierarchical, and hybrid inheritance. The key aspects are: 1) Single inheritance allows a child class to inherit from one parent class. 2) Multilevel inheritance allows a child class to inherit from another child class. 3) Hierarchical inheritance allows one parent class to have multiple child classes. 4) Hybrid inheritance combines two or more inheritance types through combinations like single/multilevel or hierarchical/single inheritance. 5) Multiple inheritance is not supported in Java to avoid complexity and ambiguity. The Open Closed Principle in SOLID

Uploaded by

Sheshgiri Sheshu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Week – 8

Inheritance in java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
 When a child class(newly defined abstraction) inherits(extends) its parent class (being
inherited abstraction), all the properties and methods of parent class becomes the
member of child class.
 In addition, child class can add new data fields(properties) and behaviors(methods),
and
 It can override methods that are inherited from its parent class.
Inheritance Basics
 The keyword extends is used to define inheritance in Java.
 The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
 In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Syntax:-
class subclass-name extends superclass-name {
// body of the class
}
Java Inheritance Example:
As displayed in the above figure , Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It
means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0

Bonus of programmer is:10000

:Types of inheritance in java:


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
1) Single inheritance

In single inheritance, a subclass inherit the features of one superclass


Single Inheritance Example:-

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the
single inheritance.

File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}

Output:
barking...
eating...
2) Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as
the derived class also act as the base class to other class i.e. a derived class in turn acts
as a base class for another class.
Multilevel Inheritance Example:-

As you can see in the example given below, BabyDog class inherits the Dog
class which again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...

3) Hierarchical Inheritance:

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class

Hierarchical Inheritance Example:


In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...

4) Hybrid Inheritance

In general, the meaning of hybrid (mixture) is made of more than one thing. In Java, the
hybrid inheritance is the composition of two or more types of inheritance. The main purpose
of using hybrid inheritance is to modularize the code into well-defined classes. It also
provides the code reusability. The hybrid inheritance can be achieved by using the following
combinations:

o Single and Multiple Inheritance (not supported but can be achieved through interface)
o Multilevel and Hierarchical Inheritance
o Hierarchical and Single Inheritance
o Multiple and Multilevel Inheritance

How hybrid inheritance works in Java?


For example, there are four classes say A, B, C, and D. Assume that the class "A" and "B"
extends the class "C". Also, another class, "D," extends the class "A". Here, the class "A" is a
parent class for child class "D" and is also a child class for parent class "C". we can
understand the example through pictorial representation.
Hierarchical and Single Inheritance
In the following Java program, we have achieved the hybrid inheritance by implementing the
combination of hierarchical and single inheritance.

Here class A and class B extends the class C that represents the hierarchical inheritance. On
the other hand, class D extends the class A that represents the single inheritance.

class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
public class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[])
{
D obj = new D();
obj.disp();
}
}

Output:

5) Multiple inheritance

When one class extends more than one classes then this is called multiple inheritance. For
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance. Java doesn’t allow multiple inheritance.
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output :
Compile Time Error

open closed principle


Open Closed Design Principle is one of the most important design principles in the world
of software development. It’s part of a group of 5 design principles commonly known by
the acronym “SOLID”
S - Single Responsibility Principle
O - Open Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation
D - Dependency Inversion
As per Robert C Martin, this principle states that software entities (classes, modules,
functions) should be open for extensions, closed for modifications. This means that a class
should be flexible enough to accommodate changes when business requirements change
without breaking the existing code.
Intent of open closed principle:
This principle separates the existing code from modified mode to provide better
stability, maintainability and minimizes the changes in the code.

Example for Open Closed Design Principle:


// Java Program to Illustrate Open Closed Design Principle
// Using Inheritance
 
// Importing input output classes
import java.io.*;
 
// Class 1
// Helper class acting as parent class
class Cake {
    // Member variable of Cake class
    private int size;
    private float weight;
 
    // Constructor for cake which sets
    // only size and dimension of cake
    public Cake(int size, float weight)
    {
        // This keyword refers to current object itself
        this.size = size;
        this.weight = weight;
    }
    // Method
    // To bake the cake
    public void bake()
    {
        // Display message only
        System.out.println(
            "Baking cake with base as vanilla");
 
        // Print and display the size and weight of the cake
        System.out.println("Size is " + this.size + " inches and weight is "
+ this.weight + " kg.");
    }
}
// Class 2
// Helper class(Child class) of class 1
class PineappleCake extends Cake {
 
    // Member variables
    private int size;
    private float weight;
 
    // Constructor
    // To set the dimension of the pineapple cake
    public PineappleCake(int size, float weight)
    {
        // Super keyword refers to parent class instance
        super(size, weight);
 
        // This keyword refer to current instance
        this.size = size;
        this.weight = weight;
    }
    // Method 1
    // To decorate the pineapple cake
    private void decorateCake()
    {
        // Display messages only
        System.out.println("Decorating cake");
        System.out.println("Adding pineapple pieces");
    }
    // Method 2
    // To add cream to pineapple cake
    private void addCream()
    {
        // Print statement
        System.out.println("Adding white cream");
    }
    // Method 3
    // To bake a pineapple cake
    public void bake()
    {
        super.bake();
 
        // Calling the above two methods created
        addCream();
        decorateCake();
 
        // Print the dimension of the pineapple cake
        System.out.println("Pineapple cake - " + this.size + " inches is ready");
    }

// Class 3
// Helper class(Child class) of class 1
class ChocolateCake extends Cake {
 
    // member variables
    private int size;
    private float weight;
    // Constructor
    // Setting the size nd weight of the chocolate cake
    public ChocolateCake(int size, float weight)
    {
        super(size, weight);
 
        this.size = size;
        this.weight = weight;
    }
    // Method 1
    // To decorate a chocolate cake
    private void decorateCake()
    {
        // Display commands only
        System.out.println("Decorating cake");
        System.out.println("Adding chocolate chips");
    }
    // Method 2
    // To add cream to chocolate cake
    private void addCream()
    {
        // Print statement
        System.out.println("Adding chocolate cream");
    }
    // Method 3
    // to bake a chocolate cake
    public void bake()
    {
        super.bake();
 
        // Calling the above two methods created
        addCream();
        decorateCake();
 
        // Print and display the dimension of chocolate cake
        System.out.println("Chocolate cake - " + this.size + " inches is ready");
    }

// Class 4
// Main class
class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an instance of pineapple cake
        // int the main() method
 
        // Custom dimension are passed as in arguments
        PineappleCake pineappleCake
            = new PineappleCake(7, 3);
 
        // Calling the bake() method of PineappleCake class
        // to bake the cake
        pineappleCake.bake();
 
        // Similarly, creating an instance of chocolate cake
        // in the main() method
        ChocolateCake chocolateCake
            = new ChocolateCake(5, 2);
 
        // Calling the bake() method of ChocolateCake class
        // to bake the cake
        chocolateCake.bake();
    }
}

Output
Baking cake with base as vanilla
Size is 7 inches and weight is 3.0 kg.
Adding white cream
Decorating cake
Adding pineapple pieces
Pineapple cake - 7 inches is ready
Baking cake with base as vanilla
Size is 5 inches and weight is 2.0 kg.
Adding chocolate cream
Decorating cake
Adding chocolate chips
Chocolate cake - 5 inches is ready
Output explanation: ‘Cake’ class is the base class. The base for every cake has a
vanilla flavor. We have two specializations i.e Pineapple and Chocolate flavor cake.
These classes use the Cake’s bake() method to make a vanilla base cake and then add
cream and decorate the cake based on the flavor.

Note:  After few days, Jane’s bakery shop sales are high. So she decides to bake cakes
with different bases to offer more varieties to her customers. With these new
requirements, we need to change the ‘Cake’ class constructor, so do the changes in the
above code will be reflected. The code changes are as below. However, we need to
modify the subclasses to accept a 3rd parameter – flavor for the code to work.

Benefits of open closed principle (ocp)


 Easier Extensibility
Needless to say, Open-closed Principle offers a better extensibility to your code. When
you write your code in such a way that it has no modification and allows extension, you
will get better extensibility on it’s own.

 Easier to Maintain
The Principle suggests using interfaces. Interfaces in code offers an additional level of
abstraction which in turn enables loose coupling. The implementations of an interface are
independent of each other and don’t need to share any code. Hence, you can easily
maintain your code with client’s keep changing requirements.

 Flexibility
When you follow the open closed principle in writing your code, you will have better
flexibility to extend it. Further, if any change request arises in future, your code will be
more flexible to extend.

You might also like