Interview question
What is Polymorphism in Java? Explain Method Overloading and Overriding. Java में Polymorphism क्या है? Method Overloading और Overriding को explain करें।
Answer
Polymorphism means 'many forms'. In Java, it allows objects to take multiple forms and methods to behave differently based on context.
// Method Overloading (Compile-time Polymorphism)
public class Calculator {
// Overloaded add methods
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
// Different parameter types
public String add(String a, String b) {
return a + b; // String concatenation
}
}
// Method Overriding (Runtime Polymorphism)
public class Animal {
public void sound() {
System.out.println('Animal makes sound');
}
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println('Dog barks');
}
}
public class Cat extends Animal {
@Override
public void sound() {
System.out.println('Cat meows');
}
}
// Usage
public class Main {
public static void main(String[] args) {
// Method Overloading
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // 15
System.out.println(calc.add(5.5, 10.5)); // 16.0
System.out.println(calc.add(5, 10, 15)); // 30
// Method Overriding (Runtime Polymorphism)
Animal dog = new Dog();
Animal cat = new Cat();
dog.sound(); // Dog barks
cat.sound(); // Cat meows
}
}Polymorphism: 'Many forms'
1. Method Overloading (Compile-time):
- Same method name, different parameters
- Parameters differ by: type, number, order
2. Method Overriding (Runtime):
- Child class override करता है parent method को
- @Override annotation use करो
- Same signature, different implementationWas this answer clear?