Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's the use of non-public top level classes?

 
David Aslan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never used non-public top level classes before, and can't think of any reason when to use them...

I played around with some code even this:



It seems that top level class Dumb can even access Verifier's protected member abc even though it isn't a subclass of Verifier!
 
Jeremy Botha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it can access it because you've marked it as protected.

Protected grants access to all implementing subclasses AND classes in the same package.

J
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15436
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never used non-public top level classes before, and can't think of any reason when to use them...

Non-public top-level classes are visible only to other classes in the same package. When you're writing a piece of software, you might want to create a class that should only be used by the other classes in the package, and which you don't want to be visible in the public API of your software.

It seems that top level class Dumb can even access Verifier's protected member abc even though it isn't a subclass of Verifier!

That is because protected means: accessible from subclasses and from classes in the same package. I don't know if you've previously programmed in C++ or another programming language that has the 'protected' keyword - this is a difference between Java and C++.
 
David Aslan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've rarely seen package level methods and functions.

In what cases would it be useful to have package level classes?

If the utility/helper class were accessing only one class, it would make better sense to make it an inner class of just that one class.

The only reason I think may be if we needed to access non public members and functions of more 2 or more classes. If that's the case, it would mean that such a non-public top level class would perform some kind of coordination glue between the other classes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic