Nope, not automatically -- if you don't define the variable yourself, it keeps the same accessibility. Let me try to explain without making this even *more* confusing: This example is from the Programming Puzzlers session at JavaOne
However, if I removed the line marked as (1), things would compile fine. Because the variable would still have protected access. Because they are within the same package, the variable is accessible. Realize the rules with methods are different, you're not allowed to override a method with more restrictive access.
Does that help? or was it more confusing? Try plopping those code snippets in a file and compile them -- play around with it a bit, that might help.
Joined: Jun 04, 2002
However, if I removed the line marked as (1), things would compile fine. Because the variable would still have protected access.
Which variable gets protected access? The variable name is public in Base. Anyway, I get the point. I'm just trying to get the C++ concepts that are not in Java out of my head. For example, the sizeof keyword in C++(which is not a keyword in Java) still gets me now and then.
Does that mean, I can't assingn the variable name(String variable) in Derived class at all? I tried with all modifiers including public? If, it is not possible, then it is a conclusion that methods defined in superclass can not be declared in subclass. But doesn't sound good to me..
This is one of those key differences between Java and C++. In C++, inheriting from a class that has a protected member makes that member private in the subclass. In Java, however, that member remains protected. Therefore, members can be inherited through multiple levels. Look at this code:
As you can see, the member i is accessible in class C. If i had become private within class B, it would not have been inherited by class C. However, I think what Jess was saying was a little misleading. Any time you define a member in a subclass that has the same name as the inherited member of its superclass, we say that we are hiding the superclass' member. It doesn't matter what accessibility you put on the superclass' or subclass' member. If you have a member in the subclass with the same name as one in the superclass, the superclass' member is hidden. Here's an example:
Notice that we output the value of i in B, not in A. You can get to the parent's member by using super, like this:
But you can't chain the keyword super (you can't do super.super.i), so you can only go up one level this way. In order to get the value of i from A in class C, class B would have to form some sort of a bridge. Be sure to check out the JLS, [/code]§220.127.116.11 Example: Hiding of Instance Variables for more details. I hope that helps, Corey