JAVA-TRICK-1: What Happens If You Override a Private Method?
Question:
Can we override a private method in Java?
Explanation:
No, private methods cannot be overridden because they are not visible to subclasses. However, if you define a method with the same name in a subclass, it is considered method hiding, not overriding.
Example:
class Parent {
private void display() {
System.out.println("Parent method");
}
}
class Child extends Parent {
private void display() {
System.out.println("Child method");
}
}
public class Test {
public static void main(String[] args) {
Parent obj = new Child();
// obj.display(); // Compilation error
}
}
Output: Compilation error because private methods are not accessible.