Loading
Java Overriding-interview

Q1. What is method overriding in Java?

Method overriding is when a subclass provides its own implementation of a method that is already defined in its parent class, with the same method name, parameters, and return type. It is used to achieve runtime polymorphism.



Q2. What are the rules for method overriding in Java?
  • The method must have the same name and parameters.
  • The return type must be the same (or covariant).
  • The method cannot be less accessible (e.g., public private).
  • The overriding method cannot throw broader checked exceptions.
  • The method must not be static, private, or final.



Q3. What is the difference between method overloading and method overriding?
  • Overloading Compile-time polymorphism, methods have the same name but different parameters.
  • Overriding Runtime polymorphism, methods have the same name and parameters but are defined in different classes (parent-child).


Q4. Write a simple Java program to demonstrate method overriding.


EXAMPLE

class Animal {

    void sound() {

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

    }

}


class Dog extends Animal {

    @Override

    void sound() {

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

    }

}


public class TestOverride {

    public static void main(String[] args) {

        Animal a = new Dog(); // Upcasting

        a.sound(); // Output: Dog barks

    }

}



Q5. Can you override a static method in Java? Write a code example to explain.


Static methods cannot be overridden, they can only be hidden

class Parent {

static void display() {

        System.out.println("Static method in Parent");

    }

}


class Child extends Parent {

    static void display() {

        System.out.println("Static method in Child");

    }

}


public class TestStaticOverride {

    public static void main(String[] args) {

        Parent p = new Child();

        p.display(); // Output: Static method in Parent

    }

}