Core Java Polymorphism Interview Questions

  1)What is polymorphism and what are the types of it in Java?

Word Polymorphism made of two words, poly and morphism. Poly means many and morphism means form so polymorphism means many form. Method overloading and method overriding are example of polymorphism in Java.

2)What is method overriding?

When child class contains same method name and same arguments but different implementation then at runtime child class is called. It is called method overriding or runtime polymorphism.

3)What is method overloading?

Method with same name but different arguments or different order of arguments is called method overloading. It is also called compile time polymorphism because it occurs at compile time.
  1. public class SumOfDigits{
  2. public static void m1(String a, int b){
  3. System.out.println("first method");
  4. }
  5. public static void m1(int a, String b){
  6. System.out.println("Second method");
  7. }
  8. public static void m1(int a, double b){
  9. System.out.println("Second method");
  10. }
  11. public static void main(String [] args){
  12. SumOfDigits.m1("ritesh",2);
  13. SumOfDigits.m1(3, "ranjan");
  14. SumOfDigits.m1(5, 6.5);
  15. }
  16. }
4)Can we overload static method?
Yes we can overload static method. But we can't overload static method with non static method.
5)can we overload main() method?
Yes we can overload main() method. main() method is static method .

6)can we override static method?
No, we can't override static method because static method resolution is based on reference class and done at compile time.
7)Can you prevent overriding a method without using final modifier?
Yes, there is a way we can prevent overriding a method without using final keyword. If we declare parent class constructor as private then parent class method won't be called in child class.
8)Can we override constructor in Java?
No, we can't override constructor in Java because constructor is associated with class  not instance of class.
9) Can we override a method which throws run-time exception without throws clause?
Yes, we can override a method which throws run-time exception. There is no rule of run-time exception in overriding.
10) Can override a method if parent class method throws checked exception?
Yes, Because there is no rule if parent class method throws checked exception. If child class method throws checked exception then parent class method must throw same checked exception or parent of that checked exception.
11)Can overloaded method have different return type?
No, overloaded method can't have different type because Java won't be able to identify which method to be called. It throws ambiguous error. 

0 comments:

Post a Comment