aspose file tools*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Protected and Public" Watch "Protected and Public" New topic
Author

Protected and Public

Bhaswati Karmakar
Ranch Hand

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

Joined: Mar 14, 2001
Posts: 147
hi
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
Samith.P.Nambiar
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.
Example:
package MyPack;
class A {
{access modifier} doSomething();
//other methods
}
class B {
//code
}
--
package OtherPack;
//some stuff
class C extends A {
//code
}
--
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
/Mike
[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.
 
Don't get me started about those stupid light bulbs.
 
subject: Protected and Public