Override “private” method in java

后端 未结 5 1092
小蘑菇
小蘑菇 2020-11-27 16:18

There something ambiguous about this idea and I need some clarifications.

My problem is when using this code:

public class B {

    private void don(         


        
5条回答
  •  我在风中等你
    2020-11-27 16:45

    private members aren't visible to any other classes, even children

    You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.

    public class A
    {
        private int calculate() {return 1;}
        public void visibleMethod()
        {
            System.out.println(calculate());
        };
    }
    
    public class B extends A
    {
        private int calculate() {return 2;}
        public void visibleMethod()
        {
            System.out.println(calculate());
        };
    }
    

    If you call A.visibleMethod() it prints out 1.

    If you call B.visibleMethod() it prints 2.

    If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.

提交回复
热议问题