Private methods in Inheritance

后端 未结 9 1785
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 04:19

Here\'s an interesting code snippet:

public class Superclass {

    public static void main (String[] args){
        Superclass obj = new Subclass();
                


        
9条回答
  •  星月不相逢
    2020-11-29 04:54

    When we define a private method with the same name in the derived class, it becomes a new method as derived class don't inherit the private members.

    Since the private method is not even visible outside the class, we can never call a base class private method from a derived class, it will throw a compilation error:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method aPrivateMethod() from the type Base is not visible

    We can use down casting to the parent class reference to call the derived class private method, which can only be accessed in that derived class.

提交回复
热议问题