Before that are you currently preparing for


1. Private Method in Parent and Same Signature in Child – Is it Overriding?

Question: What happens if a method in the parent class is private and a child class defines a method with the same signature? Is this overriding?

java

class Parent {
    private void show() {
        System.out.println("Parent show");
    }
}

class Child extends Parent {
    public void show() {
        System.out.println("Child show");
    }
}

Output:

java

Child c = new Child();
c.show(); // prints "Child show"

Answer: This is not overriding. The show() method in Parent is private, so it is not inherited by Child. The Child class is defining a new method, not overriding. It’s called method hiding, not polymorphism.


2. Static Method Hiding in Subclass

Question: How does Java handle method resolution during runtime when a subclass hides a static method from the parent class?

java

class Parent {
    static void display() {
        System.out.println("Parent static method");
    }
}

class Child extends Parent {
    static void display() {
        System.out.println("Child static method");
    }
}

Parent p = new Child();
p.display(); // Output?

Output:

sql

Parent static method

Answer: This is method hiding, not overriding. Static methods are bound at compile-time. So p.display() calls the method based on the reference type, not the actual object.


3. Protected Constructor Access Across Packages

Question: Can a subclass access the constructor of a superclass if it is marked protected and the subclass is in a different package?

java

// In package com.base
package com.base;
public class Base {
    protected Base() {
        System.out.println("Base constructor");
    }
}

// In package com.sub
package com.sub;
import com.base.Base;
public class Derived extends Base {
    public Derived() {
        super(); // Is this allowed?
    }
}