Inheritance Concept Simplified In Java

0
150
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Inheritance In Java
Inheritance In Java
Inheritance In Java

Inheritance Concept Simplified In Java:

Inheritance provides us the ability to make new,more versatile objects from already compiled objects without changing the original object.It also allow us to write new classes based on existing classes without changing the existing class in any way.Inheritance allows descendants of  a class (known as child class or subclass) to inherit all of its member elements and methods from its ancestor(Known as Parent class or super class).
The advantage of Inheritance is that it supports incremental development by allowing us to write new code without affecting the previously deployed code. By inheriting from an existing functional class,we add new methods and data members. This mechanism leaves the actual code as it is and all changes happens to be in defined  in derived class . This also helps in tracking the bugs easily.
Another aspect of Inheritance is that we don’t need the source code of the base class. Rather we need to import that class and write an extend keyword to our class.No copy paste is required.
Inheritance works as a building block providing incremental support which is very much sustainable.

The inheritance allows subclasses to inherit all the variables and methods of their parent class.
The inheritance cam be of many different forms:

  1. Single inheritance(only one super class)
  2. Multiple inheritance(several super classes)
  3. Hierarchical inheritance(One super class and many subclasses)
  4. Mutilevel inheritance(Derived from a derived class).

Single inheritance(only one super class):

Here B will contain all the public methods and variables of A.
The inheritance path is A->B

Multiple inheritance(several super classes):

Not directly supported by java but C will have all public variables and methods of A and B.
The inheritance path is A->C and B->C

Hierarchical inheritance(One super class and many subclasses):


This is the most real and common scenario when designing the real time application or issue.
The inheritance path is bird->duck
bird->cuckoo
bird->ostrich

Mutilevel inheritance(Derived from a derived class).


Class B will have all the public variables and methods of A apart from its own methods and variables and C will have all the the public methods and variables of B. Technically C will have all methods and variables of A and B.
The inheritance path is A->B->C

An Example:

class MyClass{
    public int x,y;
    MyClass(int x,int y)
    {
        this.x=x;
        this.y=y;
    }
}
class MyAnotherClass extends MyClass{
    int z;
    //inherits x,y from 
    MyAnotherClass(int x,int y,int z)
    {
    //code duplication
    //this.x=x;
    //this.y=y;
    //instead use super
    super(x,y);         
    this.z=z;
    }
    void displayValues()
    {
        System.out.println(x+y+z);
    }
}
public class TestInheritance{
    public static void main(String args[])
    {
        MyAnotherClass mac=new MyAnotherClass(3,2,2);
        mac.displayValues();
    }
} 

relax!! the code won’t compile if we do not activate super() and activate the two commented lines. This is just to show how we can do repetition of data if we do not take help from Inheritance.To avoid the repetition of code ,java uses a special keyword called Super,this can be used to refer directly to super class constructor.
this is another keyword user to tell java compiler that this will refer to current object. Let us see one more example

class Toy{
    void createNoice()
    {
        System.out.println("DUM DUM");
    }
}
class RailToy extends Toy{
    void createNoice()
    {
        System.out.println("JHIK JHIK");
    } 
}
class BusToy extends Toy{
    static boolean noHorn;
    void createNoice()
    { 
        if(noHorn)
        super.createNoice();
        else
        System.out.println("GOOO");
    }
}
public class MyToy{
    public static void main(String args[])
    {
        RailToy rt=new RailToy();
        BusToy bt=new BusToy();
        bt.noHorn=true;
        bt.createNoice();
        rt.createNoice();
        bt.noHorn=false;
        bt.createNoice();
    }
}

Output of the code:
$javac MyToy.java
$java -Xmx128M -Xms16M MyToy
DUM DUM
JHIK JHIK
GOOO
Here createNoice() method is overridden in the respective classes,with a condition that if noHorn is set to true it will invoke the Toy class’s createNoice() method.

What Is HAS-A Relationship In Java??

Inheritance -HAS-A relationship
Inheritance -HAS-A relationship

When designing our classes , our basic tendency is to design classes maximum code re usability.  Reusable code means less work and maximum output. in this post I have shown what are the prohibited concept of java in terms of extension.Now think about a scenario, I have a Tree class, I have Leave class and I have Root class as well.
Now Tree class has a methods like-

  • Consume_water();
  • Takes_CO2()
  • Release_O2()
  • Provide_shelter()

Again for Leaves class we can have the methods

  • Consume_water();
  • Takes_CO2()
  • Release_O2()

for Root class we can have  the methods..

  • Consume_water();
  • Provide_strength()

Now if you observe the methods of the classes(Tree,Leaves and Root) we can clearly say that Tree can be super class and Leave and Root can be subclass. By this approach we can get more reusable code.
so the structure could be for Tree class.

class Tree{
public void Consume_water()
{
//consumes some water
}
Public void Takes_CO2()
{
//takes x amount of CO2
}
public int Release_O2()
{
//return some o2
}
}

For Leave class

class Leave extends Tree
{
//no methods are required as all will come from Tree
}

Similarly for Root class

class Root extends Tree
{
//no methods are required as all will come from Tree
public void Provide_Strength()
{
//provide some strength to tree
}
}

Looks like we are good to go!!!

But is it ok?? Surely no. The purpose of Tree is different from Leaves so as the corresponding methods. And to make a parent child relationship the child has to follow IS-A relationship.

Leaves IS(ARE)-A Tree?
or
Root IS-A Tree?

Both the answers are false. So this is not a valid parent child relationship. Now the next question is “if we can not extend Root or leaves to Tree , then how to reuse those codes?? if not possible the code redundancy will be higher . Isn’t it?

To resolve such problem Java has come up with a concept called HAS-A Relationship.
Let us check the feature of HAS-A relationship

  • HAS-A relationship is also known as Composition or Aggregation
  • For IS-A relationship there is a keyword available called “extends” but for HAS-A relationship there is no such keyword available,Mostly we use new.
  • Code re usability is the core concept for HAS-A relationship
Class Tree{
Leaves lvs=new Leaves();
//It means Tree has leaves reference
Root rt=new Root();
//It means Tree has Roots reference

Even though HAS-A relationship resolves problems of extension.At the same time it increases dependency between the underlying components.
It creates problem in maintenance of the code.

Cyclic Inheritance: A Prohibited Approach While Designing Inheritance In Java

Cyclic Inheritance in Java
Cyclic Inheritance in Java

Cyclic Inheritance:

3 Prohibited Approaches While Designing Inheritance In Java.Cyclic Inheritance is prohibited in java.

class A extends B
{
//do some code
}
class B extends A
{
//do some code
}

let me show one more example

class A extends A{
//do some code
}

For such cases we are going to get compilation error during compilation but we need to take care while designing this class. It is said the first example of cyclic reference is generally occurred while design real time complex java project.
Second important aspect of java class design , multiple inheritance. This is not supported in java.

class A
{
//some code
}
class B
{
//some code
}
class c extends A,B
{
//some code
}

This is also one kind of Cyclic reference.

Say for this example Class B and Class C is derived from Class A and A is having a method which is overridden  in Class B and Class C. Now if a fourth class D trying to extend both the class,by the principal of inheritance both the modified method will come to D. this creates a ambiguity for compiler which one to take.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
READ  The Cause At the rear of the Massive Demand from customers of Python Builders

LEAVE A REPLY

Please enter your comment!
Please enter your name here