Polymorphism Interview Questions in Java
Interview Questions on Polymorphism in Java
.
What is Polymorphism ?
The ability to define a function in multiple forms is called Polymorphism.
What is Overloading ?
Whenever several methods have same names with;
- Different method signature and different number or type of parameters.
- Same method signature but different number of parameters.
- Same method signature and same number of parameters but of different type
It is determined at the compile time.
What is method overriding ?
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. It is determined at the run time.
Difference between method overloading and method Overloading ?
Method overloading is determined at the compile time and method overriding is determined at the run time
How to achieve polymorphism in Java ?
How to achieve polymorphism in Java ?
In Java, static polymorphism is achieved through method overloading and method overriding.
Types of polymorphism in Java ?
In Java, there are two types of polymorphism.
- Compile time polymorphism (static binding or method overloading)
- Runtime polymorphism (dynamic binding or method overriding)
How to achieve static polymorphism in Java ?
In Java, static polymorphism is achieved through method overloading.
How to achieve dynamic polymorphism in Java ?
In Java, dynamic polymorphism is achieved through method overriding.
What is Compile time polymorphism ?
As the meaning is implicit, this is used to write the program in such a way, that flow of control is decided in compile time itself. It is achieved using method overloading.
Example
public static int add(int a, int b) { ...... ...... } public static double add(double a, double b) { ...... ...... } public static float add(float a, float b) { ...... ...... }
What is Runtime polymorphism ?
Run time Polymorphism also known as method overriding and it is achieve at runtime.
Example
class Vehicle { public void move() { System.out.println("Vehicles can move !!!!"); } } class MotorBike extends Vehicle { public void move() { System.out.println("MotorBike can move and accelerate too!!!"); } } class Demo { public static void main(String[] args) { Vehicle obj=new MotorBike(); obj.move(); // prints message MotorBike can move and accelerate too!!! obj=new Vehicle(); obj.move(); // prints message Vehicles can move!! } }