Tuesday, 26 July 2016

Java Code Showing example of Inheritence

Inheritence is a mechanism by which we inherit all the features of super class in sub class through extends keyword. By extending super class and creating sub class object we have 
1 > by default super class constructor available in sub class
2 > we can call super class variable  
3 > we can call super class method

How inheritance implemented in java?
Inheritance can be implemented in JAVA using below two keywords.
1 > extends
2 > implements 

extends Keyword Example :-
class Customer{
int num = 50;
public Customer() {
System.out.println("Super Class Constructor");
}
void show(){
System.out.println("Super Class Method");
}
}
public class InheritenceExample extends Customer{
public static void main(String[] args) {
InheritenceExample i = new InheritenceExample();
System.out.println("Super Class Variable : "+i.num);
i.show();
}
}

implements Keyword Example :-
The interface keyword is used to declare an interface , a class implements an interface , in interface
1 > All methods are by default Abstract and public.
2 > All variable are by default static and final .
3 > An interface can extends multiple interfaces.
4 > One interface extends another interface not implements

interface Service{
int num = 20;
void show();
}
public class Example implements Service {

@Override
public void show() {
System.out.println("show method");
}
public static void main(String[] args) {
ImplementsKeywordExample i =new ImplementsKeywordExample();
System.out.println("VARIABLE :- "+i.num);
i.show();
}

}

There are two types of inheritance
1 > Multilevel Inheritance : -
class AA{

}class BB extends AA {

}class CC extends BB {

}
2 > Multiple Inheritance : -
Multiple Inheritence is not supported by java because of Diamond Problem .In multiple inheritance there is every chance of multiple properties of multiple objects with  the same name available to the sub class object with same priorities leads for the ambiguity.

class M{

}class N extends M{
}class O extends N{
}class P extends N,O { // not supported by java leads to syntax error. 

}

No comments:

Post a Comment