JAVA-TRICK-1: What Happens If You Override a Private Method?

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.

要查看或添加评论,请登录

Chamseddine Toujani的更多文章

社区洞察

其他会员也浏览了