This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Coming from a c++ background i was surprised to read that protected fields in a class were accessible to the instances of the class.
I was however a bit confused b/w the default (no access modifier) and the protected modifier. Could anyone please give a simple explaination on their difference.
I did look up on the internet and even oracle http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html has something like this
Modifier | Class | Package | Subclass | World
public | Y | Y | Y | Y
protected | Y | Y | Y | N
no modifier | Y | Y | N | N
private | Y | N | N | N
could you kindly tell me what the world is ?? thanks...
That's right. And instances of simple_class can access private members of simple_class. But in your earlier example, you weren't in simple_class - you were trying to access the private member from the Test class.
Basically, a private field or method can be accessed by any "instance of the class". This means that any method of any instance of that same class can access that private field or private method -- or the class itself (if the private field or method is static). We are talking about the same class.
In your example, you seem to imply that any class (even a different class type) can access any private field of an instance that it has an instance of. And no, that is not allowed in Java -- for private, default, or protected fields or methods.
Matthew Brown wrote:That's right. And instances of simple_class can access private members of simple_class. But in your earlier example, you weren't in simple_class - you were trying to access the private member from the Test class.
hmm.. I think this is a case of misunderstanding earlier i assumed you were saying something like