Skip to content

Instantly share code, notes, and snippets.

@dumbbellcode
Last active September 5, 2019 16:11
Show Gist options
  • Save dumbbellcode/bb9731dde536cf26693c8b141b12b3e8 to your computer and use it in GitHub Desktop.
Save dumbbellcode/bb9731dde536cf26693c8b141b12b3e8 to your computer and use it in GitHub Desktop.
Polymorphism(Compiletime vs Runtime),Method Overloading and Method Overriding in java.
public class Polymorphism{
public static void main(String []args){
Base b1 = new Base();
Derived d1 = new Derived();
Base b2 = new Base();
Derived d2 = new Derived();
System.out.println("\n\n");
//Compiletime Polymorphism ->Method Overloading(i.e function overloading)
//(Methods have same name,diff parameters,inside same class)
//Runtime Polymorphism ->Method Overriding ->Dynamic Method Dispatch
//(Methods have same name,same parameters one in base class,other in derived class)
/************************/
Base b3 = new Derived();// UPCASTING
//Reference variable of parent class points(refers) to object of child class
b3.func(); //same function present in both base and derived
//But b3.func() calls the func() from derived class
b3.func1();
//Here b3.func2() gives error, can't find symbol
System.out.println("\n\n");
//Derived d3 = new Base(); -> error "Base cannot be converted to Derived"
//The bank example at javatpoint is best to understand importance of upcasting
/*********************/
}
}
class Base
{ int x;
static int y;
Base()
{ x=x+1;y=y+1;
System.out.println("Base Constructor "+x+" "+y);
}
void func1()
{
System.out.println("Base Fuction");
}
void func()
{
System.out.println("Base Fuction with same name func");
}
}
class Derived extends Base
{
Derived()//base constructor is called everytime derived constructor is called
{ x=x+1;y=y+1;
System.out.println("Derived Constructor "+x+" "+y);
}
void func2()
{
System.out.println("Derived Function");
}
void func()//method overriding
{
System.out.println("Derived Fuction with same name func");
}
}
/* OUTPUT
Base Constructor 1 1
Base Constructor 1 2
Derived Constructor 2 3
Base Constructor 1 4
Base Constructor 1 5
Derived Constructor 2 6
Base Constructor 1 7
Derived Constructor 2 8
Base Fuction
Derived Fuction with same name func
*/
/*
Inheritence:
https://www.geeksforgeeks.org/inheritance-in-java/
https://www.geeksforgeeks.org/gfact-52-java-object-creation-of-inherited-classes/
Polymorphism
https://www.javatpoint.com/runtime-polymorphism-in-java (best resource)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment