Can I override a private method in Java?

前端 未结 10 1182
天涯浪人
天涯浪人 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:16

    If you really wanted to do this using reflection, you could:

    public class SuperClass {
    
        private final Method getInt;
    
        public SuperClass() {
            /** Find the appropriate method to call and cache it. **/
            Method getInt = null;
            try {
                getInt = getClass().getDeclaredMethod("getInt");
            }
            catch (NoSuchMethodException e) {
                try {
                    getInt = SuperClass.class.getDeclaredMethod("getInt");
                } catch (NoSuchMethodException e1) {
                    throw new RuntimeException(e1);
                }
            }
            getInt.setAccessible(true);
            this.getInt = getInt;
        }
    
        public void print() {
            int val = 0;
            try {
                val = (Integer) getInt.invoke(this);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            System.out.println(val);
        }
    
        private int getInt() {
            return 1;
        }
    }
    
    public class SubClass extends SuperClass {
        public int getInt() {
            return 2;
        }
    
        public static void main(String[] args) throws Exception {
            new SubClass().print();
        }
    }
    

    I suspect you want to design your program differently, rather than take this approach. It's not performant, and it will definitely catch anybody who extends SuperClass by surprise.

    Note that the subclass's getInt() method can be private if you use reflection this way. Again, taking this approach is almost definitely a Bad Idea, for at least the two reasons mentioned. Chances are you can accomplish your goals another way. Package protection is really not an option?

    0 讨论(0)
  • 2020-11-29 09:16

    Read this carefully,

    PRIVATE methods are NOT INHERITED... As they are not inherited, they CANNOT BE OVERRIDDEN

    0 讨论(0)
  • 2020-11-29 09:17

    I couldn't do this with reflection, but I have figured out a way to do it via instrumentation. I've used ASM, as suggested on Dhruba Bandopadhyay's blog. If you're interested, you can look at my code (there's too much to post it here).

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-29 09:21

    No, you can't. You can construct a program which look like it should be able to do this, using the fact that code within an outer class can access nested class's private members. However, private methods still can't actually be overridden. Example:

    public class Test {
    
        public static class Superclass {
            private void foo() {
                System.out.println("Superclass.foo");
            }
        }
    
        public static class Subclass extends Superclass {
            private void foo() {
                System.out.println("Subclass.foo");
                // Looks like it shouldn't work, but does...
                super.foo();
            }
        }
    
        public static void main(String[] args) throws Exception {
            Superclass x = new Subclass();
            // Only calls Superclass.foo...
            x.foo();
        }
    }
    

    Given that this would be the only situation in which it was feasible to override a private method, it's no great loss that it's not supported.

    If you want to change the behaviour of a private member of your superclass, your design is broken, basically.

    0 讨论(0)
  • 2020-11-29 09:21

    can you pass var by reference -> classes using java ?

    because if it's ever possible: above problem could be rewritten as:

    (Note this is for specification purpose only)

    VB:

    function(ByRef intX as Integer) //value can be explicitly changed but not the method itself :P end function

    so much more like that i guess...

    0 讨论(0)
提交回复
热议问题