Reputation: 1
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?
Upvotes: 0
Views: 95
Reputation: 1262
Subclasses do not inherit private members in java. Subclass doesn't know all thing about parent class
Upvotes: 1
Reputation: 9058
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.
Upvotes: 0
Reputation: 466
Would it not be safe to assume that the sub class has its own private member version and be able to override in Java?
NO
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
Upvotes: 0