GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Second page of book, first question - Access modifiers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Second page of book, first question - Access modifiers" Watch "Second page of book, first question - Access modifiers" New topic
Author

Second page of book, first question - Access modifiers

Monica Moncho
Ranch Hand

Joined: Dec 01, 2004
Posts: 31
HI,

I just started the java certification book and already I see that I know much less than I thought. I see modifiers PRIVATE for method or variable, PROTECTED for method or variable, and PUBLIC for class, method or variable.

the uppercase are mine but, does it mean we cannot have a PROTECTED class? or does it mean if we say nothing it means PROTECTED? Or does it not matter? and why?

I guess I'm confused with just the second page. anybody can help me?

thanks!
kalpana Kumar
Ranch Hand

Joined: Jul 03, 2003
Posts: 65
Monica,
You are partly correct in understanding that

PRIVATE for method or variable, PROTECTED for method or variable, and PUBLIC for class, method or variable

PRIVATE - Private variables are only visible from within the same class as they are created.in. This means they are NOT visible within sub classes.
Private classes would always be nested.

PUBLIC - public class has global scope, and an instance can be created from anywhere within or outside of a program.

PROTECTED (classes would be nested) -A protected variable is visible within a class, and in sub classes, the same package but not elsewhere. Any class in the same directory is considered to be in the default package, and thus protected classes will be visible.

DEFAULT - A variable defined with no access modifier is said to have default visibility. Default visibility means a variable can be seen within the class, and from elsewhere within the same package,
but not from sub-classes that are not in the same package(this is the major difference between DEFAULT and PROTECTED)

Hope this gave you an idea.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
As for classes, regular top-level classes can only use the PUBLIC modifier or no modifier at all (DEFAULT access). In other words, regular top-level classes cannot be PRIVATE or PROTECTED.

Notice that I specify that these rules apply to "regular top-level" classes. This is my feeble attempt to differentiate from inner classes, which can, afaik, use any of the access modifiers.

Layne


Java API Documentation
The Java Tutorial
Monica Moncho
Ranch Hand

Joined: Dec 01, 2004
Posts: 31
wow,

thank you very much to both of you. This is much clearer now. I didn't think about inner classes, I guess it makes sense then.

Thanks again, this was great.!
 
GeeCON Prague 2014
 
subject: Second page of book, first question - Access modifiers