• Post Reply Bookmark Topic Watch Topic
  • New Topic

class level access modifier  RSS feed

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can have member level modifier as public , protected, private or no modifier. If a constructor is "no modifier" constructor, then that class can not be instantiated outside the package.
Then what is the point in having class level "no modifier" ? That again provides the same functionality. Is there any advantage of making class level modifier as "no modifier" ? Or is there some functionality, we can not achieve by specifying constructor as "no modifier" that we can achieve by making class level access as "no modifier" ?

Thanks
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The two uses are very different. If you specify the class as package private, it can not be seen outside the package at all. If its constructor is package private, it simply can not be instantiated outside the package.

There may be occasions where you want a class to be usable outside the package, but you want control over how instances of that class are created. In this case, another class in the package can create new instances of the first class, and provide it to the outside world.
 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a class is package private, still another class from same package can create an instance of this class and provide it to outside world, like it can be done with when constructor is package private, is this right ? Then whats the difference between package private class or package private constructor ?

Thanks
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference is that if the class is package private, a class outside the package can not see it. If class A is package private, and a reference of it is returned by a method of some class B in the same package, class C in another package can only assign that reference to a variable of type Object, or whatever other public classes or interfaces are supertypes of A. Example:



C can not use any of the features that A defines, because A is not visible outside the package. If A was public, C would be able to use these features, but it would still have to get an instance of A through B.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!