💻Step 14: Oops- 2nd Concept: Polymorphism: 9th hour + code

Learn with youtube video –

java polymorphism and types

 

💡Polymorphism-

💡Definition –

Generally means “one name, many forms”
-in java, polymorphism means “one name of multiple methods, but different outputs.

💡Rule of polymorphism-

method name must be same

💡Types of polymorphism-

1- Compile time polymorphism/static method binding
2- Runtime polymorphism/dynamic method binding

Quick Comparison between compile-time polymorphism and runtime polymorphism in Java:

Compile-time PolymorphismRuntime Polymorphism
Also known asStatic polymorphismDynamic polymorphism
Achieved throughMethod overloadingMethod overriding
Compiler determines methodAt compile timeAt runtime
Requires inheritanceNoYes
PerformanceFaster and more efficientSlower and less efficient

💡1- Compile time polymorphism

-Calling method is decided at compile time
– In java, this is achieved by Method Overloading

💡(i) Method overloading

Rules of method overloading-

-only 1 class is required
-parameter must be different
-return type can be different or same

💡2- Runtime polymorphism

-Calling method is decided at runtime
-in java, this is achieved by method overriding

💡(ii) Method overriding

Rules of method overriding-

-at least 2 classes are required
-parameters must be same
-return type must be same

code samples are here

1- Compile time polymorphism


package polymorphism13;

public class ExampleCompilePoly {

void show(int a){
System.out.println("hello the number is "+a);
}

void show(String a){
System.out.println("hello the text is "+a);
}

public static void main(String[] args) {
ExampleCompilePoly e1=new ExampleCompilePoly();
e1.show(25); //will call first show method
}

}

Run this Program ▶️

2- Runtime polymorphism


package polymorphism13;

class A{
void display(){
System.out.println("hi");
}
}

public class ExampleRuntimePoly extends A {

void display(){
System.out.println("bye");
}
public static void main(String[] args) {

ExampleRuntimePoly n1 = new ExampleRuntimePoly();
n1.display(); //will call second display method
}
}

Run this Program ▶️

Interview Questions —

  • what is polymorphism in real world?
  • What is difference between method overloading and method overriding?

Leave a Reply

Your email address will not be published. Required fields are marked *