• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2934
  • Last Modified:

protected class

Why can't the class in java be protected ?
Please explain in detail.
0
xzyeena
Asked:
xzyeena
1 Solution
 
jerchCommented:
Hi xzyeena...
Because it doesn't make sense. protected features (methods, attributes and nested class) of a class are accessible by the class itself, class within the same package and classes that extends the class. The difference between package and protected lies in the accesibily of the subclass to the features of the superclass. Then, if you have a class with protected accessibility will it make any difference compared to package? I hope this answers your question.

By the way, "Why can't the class in java be protected?" should be rephrased as "Why can't the TOP-LEVEL class in java be protected?"  because nested classes can be protected.

best regards...
Jerson

0
 
xxMariusxxCommented:
You either want things to be visible to the outside world, or you don't.  If everyone should be able to see something, you make it public.  If you only want members of your class to see something, you make it private.

However, if you make something private, and then you subclass later on, your subclass won't have access to the private members of its superclass.  So in order to make something for all intents and purposes 'private', yet still visible to subclasses that extend your class, you make it 'protected'.

Doesn't make sense to create an entire class that the outside world cannot see (private)...and even less sense to say, "I'll hide it from the outside world...but in case they wanna subclass it...."  ...if you can't see it to begin with, you can't subclass it.

So classes are public or package friendly (no visibility modifier).  As Jerson said, though, you're free to make inner classes however you like.

Marius
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now