Can I override a private method in Java?

前端 未结 10 1241
天涯浪人
天涯浪人 2020-11-29 08:26

I know I can use reflection to invoke a private method, and to get or set the value of a private variable, but I want to override a method.

public class Supe         


        
10条回答
  •  难免孤独
    2020-11-29 09:18

    You can't override a private method, but you can introduce/redefine one in a derived class.Like:

    class Super
    {
       private void fun()
       {
       }
    }
    
    class Child extends Super
    {
        private void fun()
        {
        }
    }
    

    In this you are not overriding this fun() in the Child class you are defining a new method with the same name but if you try to use @override on the top of fun() of Child class than you will get compile time error because you are forcing to override this fun() else you are just redefining the new fun() in Child class

提交回复
热议问题