New Doubt: from SCJP6.0 K&B MockExam-1

I think that Line 12 should give a compile Error "numbers has private access in Numbers"

Although negate() function is inside Numbers class, the negatives object is a new one.
And numbers.add(-n) is a direct access, which should be allowed only within methods of numbers object, and not this object.

The following code gives compile error, as private member numbers is accessed directly:

OCPJP6

Trivikram Kamat
Ranch Hand

Joined: Sep 26, 2010
Posts: 155

posted Sep 28, 2010 03:32:49

0

Just checked in C++, it behaves the same way

This code compiles properly:

But this one gives compiler error 'int Numbers::data' is private within this context

Can someone please explain how the access modifiers work in this case (in Java).

Private means in Java, that private members can be accessed in the same Class, not from other class. This is way, you got Error in your codes. You are accessing a private member from another class. Private isn't private for same class instances in Java, that's the previous code works.

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|

Trivikram Kamat
Ranch Hand

Joined: Sep 26, 2010
Posts: 155

posted Sep 30, 2010 23:33:22

0

Thanks Abhimaran for the explanation. So, Private members are private to the class and not the specific objects.
This is one way using which objects of same class can access private members of each other.

After this, I wrote some test codes for checking protected access modifier.
Protected members can be directly accessed through objects of Base class from the derived classes within the same package.
But it doesn't work with subclasses in different package, where one needs to use Derived class object to access base class protected members.

This is because protected members are accessible in kids + subclasses, as given in K&B
But in subclasses from different packages, they're accessible only through subclass object, and not through superclass object.

ClassB compiles fine, if following changes are done on Line 8:

This is just the way I understood the concept.
No questions about anything...