Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Protected and Public Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Protected and Public" Watch "Protected and Public" New topic

Protected and Public

Bhaswati Karmakar
Ranch Hand

Joined: May 10, 2001
Posts: 32
Could you please explain, what is the difference between the protected and public access modifier ?
Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
1. a public member variable can be accessed anywhere in the program
2. a protected memeber variable can be acccessed by a member of the class in the same package or a member of a subclass of this class but in another package
thats basically what the definitions say .... tell me what exactly u dont understand
Mikael Jonasson
Ranch Hand

Joined: May 16, 2001
Posts: 158
This depends a bit about how much you know about the access modifiers overall.
The pure differens between protected and public is that public doesn't put any restrictions on the variable/method. If you can reference the class (or subclass thereof) you can access the variable/method.
Setting something to protected means that you restrict the access some. Now only classes in the same package or subclasses of the current class can access it.
package MyPack;
class A {
{access modifier} doSomething();
//other methods
class B {
package OtherPack;
//some stuff
class C extends A {
package thirdPack;
//Some stuff
class D {
If you look at the classes above, you noticed that I omitted the access modifier on method doSomething(). If we were to put public there, all four classes (A,B,C,D) will be able to access it, as long as they know about class A (which A obviously do, it's called 'this').
If instead we put protected on it, only A,B & C will be able to access it. A because it's the same class (and same package), B because it's the same package, and C because it's a sub-class of A.
Hope that helped
[This message has been edited by Mikael Jonasson (edited May 17, 2001).]
Bhaswati Karmakar
Ranch Hand

Joined: May 10, 2001
Posts: 32
Great. Thanks to both of you.
I agree. Here's the link:
subject: Protected and Public
It's not a secret anymore!