Inheritance in Java
Inheritance in Java
➢ Single Inheritance with Example :- When a class inherits another class, it is known as
a single inheritance.
Example :–
class Parent {
void disp() {
System.out.println("Hello, I am Srimanta Maity,father of Subhankar");
}
}
class Child1 extends Parent {
void show() {
System.out.println("Hi, I am Subhankar.");
}
}
public class singleInheritance {
public static void main(String[] args) {
Child1 c = new Child1();
c.disp();
c.show();
}
}
Output –
Hello, I am Srimanta Maity,father of Subhankar
Hi, I am Subhankar.
Example :-
class Parent {
void disp() {
System.out.println("Hello, I am Srimanta Maity,father of Subhankar");
}
}
class Son extends Parent {
void show() {
System.out.println("Hi, I am Subhankar.");
}
}
class Child extends Son {
void view() {
System.out.println("Hi, I am a child.");
}
}
public class multilevelInheritance {
public static void main(String[] args) {
Child c = new Child();
c.view();
c.show();
c.disp();
}
}
Output: -
Hi, I am a child.
Hi, I am Subhankar.
Example –
class Parent {
void disp1() {
System.out.println("Hello, I am Srimanta Maity,father of Bubu & Debu");
}
}
class Son1 extends Parent {
void show() {
System.out.println("Hi, I am Bubu.");
}
}
class son2 extends Parent {
void show() {
System.out.println("Hi, I am Debu.");
}
}
public class hierarchicalInherit {
public static void main(String[] args) {
Son1 s1 = new Son1();
son2 s2 = new son2();
s2.disp1();
s2.show();
s1.disp1();
s1.show();
}
}
Output –
Hello, I am Srimanta Maity,father of Bubu & Debu
Hi, I am Debu.
Hi, I am Bubu.
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.
Example :–
interface Father {
double ht = 5.6;
}
interface Mother {
double ht = 5.0;
}
class Son4 implements Father, Mother {
double ht;
void calculate() {
ht = (Father.ht + Mother.ht) / 2;
System.out.println("Son height is average of father &
mother=" + ht);
}
}
public class multipleInheritance {
public static void main(String[] args) {
Son4 s = new Son4();
s.calculate();
}
}
Output:
Son height is average of father & mother=5.3