Most of the Java lover say that Java does not support multiple inheritance but this is not hundred percent correct. We will try to understand inheritance in java in detail with all possibilities.
“A relationship among classes where one class share the structure and/or behaviour of one of more classes. This mechanism is known as the name of inheritance.”
Type of inheritance purpose
1. Implementation inheritance Code Reusability and Runtime Polymorphism
2. Interface inheritance Runtime Polymorphism
Syntax: implementation inheritance
Class ClassName extends SuperClassName{
//additional methods of class
}
Syntax: implementing an interface
Class ClassName implements InterfaceName{
// public definition of all the methods of interface
//additional methods of class
}
Java support multiple interface inheritance but not support multiple implementation inheritance that mean one class cannot extends more than one classes but implements more than one interfaces and also an interface extends one or more than one interface using extends keyword. Like below
interface Person {
}
interface Address{
}
interface User extends Person,Address{
}
Why Java not support multiple implementation inheritance?
There are several reasons
1. When two base classes contain a method of same name then complier does not know whether method is member of first class or second class. Consider the below situation
class Super1{
void disp(){}
}
class Super2{
void disp(){}
}
class Sub extends Super1, Super2{
}
Class Test{
Public static void main(String as[]){
Sub sub=new Sub();
sub.disp(); //This is ambiguous
}
2. Possibilities of the sub class having multiple copies of the same base class. Consider the below situation
class A{
int x;
}
class B extends A {
int y;
}
class C extends A{
int z;
}
class D extends B,C{
int d;
}
class Test{
Public static void main(String as[]){
D d1=new D();
d1.x=10; // This is ambiguous
}
Problem:
D inherits one copy of x through B and another copy through C.
“This type of situation not be created in java, java has restricted multiple implementation inheritance.”
No comments:
Post a Comment