简体   繁体   中英

Why can we not override private members of a super class in a sub class?

Is not the sub class inheriting all of the members from the super class regardless, so why not be able to override the private member variables from the super class? Would it not be safe to assume that the sub class has its own private member version and be able to override it in Java?

Subclasses do not inherit private members in java. Subclass doesn't know all thing about parent class

Would it not be safe to assume that the sub class has its own private member version and be able to override in Java?

Just think to write a library and not just code for only your current project.

Your classes can be inherited to add more functionality, but the user of your library should not change your behavior.

A simple example could be the AtomicInteger Java class, it has private volatile int value; field. Now, if you could access at that member just inheriting the class, would mean that you could change the value loosing all AtomicInteger thread safety.

I'm sure that if you look in java.util package you will find a lot of similar cases, in which some field is and must be managed internally and accessed only from methods

You've gotten some hints from the other info, but here's an example. Imagine two classes, Foo and Bar. Bar inherits from Foo. Here's a simple implementation of each:

public class Foo {
    private void myPrivateMethod() { System.out.printf("myPrivateMethod()\n"); }
    public void myPublicMethod() { System.out.printf("myPublicMethod()\n"); }
}

public class Bar extends Foo {
    public void barPublicMethod() {
        System.out.printf("This is barPublicMethod()!\n");

        myPublicMethod();
        myPrivateMethod();
    }

    public static void main(String[] args) {
        System.out.printf("This is main!\n");

        Bar bar = new Bar();
        bar.barPublicMethod();
    }
}

If you try to compile this code, you get this error:

$ javac Foo.java Bar.java && java Bar
Bar.java:6: error: cannot find symbol
        myPrivateMethod();
        ^
  symbol:   method myPrivateMethod()
  location: class Bar
1 error

If you remove the call to myPrivateMethod(), it works. This is the nature of private methods.

Bar knows NOTHING about the private methods of Foo. NOTHING. Which means you can't override them, because Bar doesn't even know they exist. That's what private means.

Bar can't do one single thing with private methods from Foo. Nothing. If you want Bar to be able to override them, you need to change the definition in Foo to protected or public.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM