What is Inheritance
Lets Discuss Today,What inheritance really is...
Inheritance means inheriting properties from parent like A son inherites properties of his father....
But In Java programming ......
A class inherites properties of its parent class
So we can say "Inheritance is process in which one object acquires all the properties and behaviours of its parent class"
Inheritance represents IS-A relationship..
Note -static members can not be inheritaed in child class because static member always stick with its class.All the static member gets memory at loading time And Inheritance is a runtime phenomina.So it can not inheritaed ..
extends and implements are keywords in java which are used to inherit a class and interface respectivly
There Are Two Main Reason Why We Use Inheritance In Java
1- For Method Overriding (Runtime polymorphism)
2- For Code reusability
Type of Inheritance
1-Single Inheritance
2-multilevel Inheritance
3-Hierarchical Inheritance
4-multiple Inheritance (It is not supported by java)
5-Hybrid Inheritance
Q-> Why Java does not support multiple Inheritance ?
Ans- Multiple Inheritance means One class is inheriting(extending) two class.So It may be possible that Both classes have same variable .Thus at the time of accessing that variable ,there will be ambiguity to call variable
Method Overriding
Overriding means when we rewrite a method again for its improvement
" If subclass (child class) has the same method as declared in the parent class, it is known as
Method Overriding"
" If subclass (child class) has the same method as declared in the parent class, it is known as
Method Overriding"
Rule 1-
Methods must have the same name And same parameter
Rule-2
Access Modifier of child class method must be same OR wider than parent class method
1-Single Inheritance
class A{
public void operation(int a,int b){
System.out.println(a+b);
}
}
public class B extends A{
public void operation(int a,int b){
System.out.println(a*b);
}
public static void main(String arg[]){
A a=new B();
a.operation(3,4);
}
}
output is
12
multilevel inheritance
class A{
public void operation(int a,int b){
System.out.println(a+b);
}
}
class B extends A{
public void operation(int a,int b){
System.out.println(a*b);
}
}
public class C extends B{
public void operation(int a,int b){
System.out.println("This is class C ");
System.out.println(a-b);
}
public static void main(String arg[]){
C c=new C();
c.operation(4,3);
}
}
output is
1