Header Ads

Cyclic Inheritance: A Prohibited Approach While Designing Inheritance In Java

3 Prohibited Approaches While Designing Inheritance In Java
In my last post I have written about Inheritance and IS-A relationship here. That post will talk about what is an inheritance and how to implement that. Objective of this post is little different. This post talks about what we can not do with respect to inheritance.

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.

Secondly by theory, even if D is trying to override all the conflicting methods, then it has to reinvent the wheel. Code redundancy will increase. It will surely destroy the main idea behind inheritance i.e-code reusability.

This diagram is popularly known as diamond diagram for Multiple inheritance.

Multiple inheritance is not directly supported by java. But by using interface we can implement the same. A class can not extend more than one class at a time but for interface there is no such limitation.
Now wait for one more concept. Every class in java extends class Object. Class Object is the superclass for all class we create in java.It is the job for compiler to check and update the .class file accordingly.
Like if you write a class like below:
class A{
//do some activity
}

The java compiler will transform the same into a .class file as..
class A extends Object{
//do some activity
 }
Any class that does not explicitly extend another class, implicitly extends object.
This is how, java has removed diamond problem.
Powered by Blogger.