Multi-level inheritance:
public class A{
protected int x;
public A(int x){
this.x=x;
}
}
public class B extends A{
protected float y;
public B(int x,float y){
super(x);
this.y=y;
}
public class C extends B{
protected String s;
public C(int x,float y,String s){
super(x,y);
this.s=s;
}
public void show(){
System.out.println(super.x);
System.out.println(super.y);
System.out.println(this.s);
}
public static void main(String[] args){
C c=new C(10,3.4f,"msg");
c.show();
}
}
Hierarchical Inheritance:
public class Input{
protected int x,y,res;
public Input(){
Scanner sc=new Scanner(System.in);
System.out.print("X:");
this.x=sc.nextInt();
System.out.print("Y:");
this.y=sc.nextInt();
}
public void show(){
System.out.println(this.res);
}
}
public class Addition extends Input{
public Addition(){
super();
}
public void sum(){
super.res=super.x+super.y;
}
}
public class Subtraction extends Input{
public void sub(){
super.res=super.x-super.y;
}
}
public class Main{
public static void main(String[] args){
Addition add=new Addition();
Subtraction sub=new Subtraction();
add.sum();
sub.sub();
System.out.print("Addition:");
add.show();
System.out.print("Subtraction:");
sub.show();
}
}
Binding:
* Process of replacing a function call with function body
Compile-time binding -> method body is replace the function during compile time
Run-time binding -> method body is selected during run-time
Method Overloading:(static polymorphism or compile-time)
public class Exam {
public void show() {
System.out.println("Welcome");
}
public void show(String name) {
System.out.println("Hi,"+name);
}
public void show(String name,String role) {
System.out.println("Hi,"+role+", your name is "+name);
}
}
public class Main {
public static void main(String[] args) {
Exam e=new Exam();
e.show();// method with 0 parameters
e.show("Rakesh");
e.show("Rajesh","Admin");
}
public class A{
int x;
A(){
this.x=0;
}
A(int x){
this.x=x;
}
}
A a=new A(); // will call default constructor
//a.x => 0
A a1=new A(20); // will call param constructor
//a1.x=> 20