Loading
Java Polymorphism-interview

Q1. What is polymorphism in Java?

Polymorphism in Java is the ability of an object to take many forms. It allows the same method name to behave differently based on the object or arguments. There are two main types: compile-time (method overloading) and runtime (method overriding).



Q2. What is the difference between method overloading and method overriding?

Method Overloading: Happens at compile time. Same method name but different parameter lists (number or type of arguments).

Method Overriding: Happens at runtime. A subclass provides its own implementation of a method defined in the parent class.



Q3. Can we override a static method in Java? Why or why not?

No, we cannot override a static method because static methods are bound at compile time (class-level), while overriding requires runtime binding (object-level). However, we can hide a static method by redefining it in the subclass.



Q4. Can you write a code example of method overloading in Java?

EXAMPLE


class Calculator {

    // Method overloading

    int add(int a, int b) {

        return a + b;

    }

    double add(double a, double b) {

        return a + b;

    }

}


public class OverloadingDemo {

    public static void main(String[] args) {

        Calculator calc = new Calculator();

        System.out.println("Sum of integers: " + calc.add(5, 10));

        System.out.println("Sum of doubles: " + calc.add(5.5, 10.5));

    }

}









OUTPUT


Sum of integers: 15 Sum of doubles: 16.0



Q5. Can you write a code example of method overriding in Java? 

EXAMPLE


class Animal {

    void sound() {

        System.out.println("Animal makes a sound");

    }

}


class Dog extends Animal {

    @Override

    void sound() {

        System.out.println("Dog barks");

    }

}


class Animal {

    void sound() {

        System.out.println("Animal makes a sound");

    }

}


class Dog extends Animal {

    @Override

    void sound() {

        System.out.println("Dog barks");

    }

}


OUTPUT


Dog barks