I've just been doing a bit of research on this and have not been able to find a definitive answer. It seems most likely that it is just an oversight on the part of the Java language designers and since it doesn't actually do any harm it has been left. It's no different really from putting a public
method into a private
class. Nothing stops you doing this, even though there is no way to actually access that public
method.
Certainly NetBeans gives you the warning "Exporting non-public type through public API" when you try to do this. I expect most other environments will give a similar warning.
The returned object is entirely useless to anyone who tries to use it (unless they use reflection), pretty much all they can do is store it into an Object
(or any other super class that they do have access to) and then pass that Object
around.
You could potentially want to do this if the passed Object
is being used as a "handle" that gets passed around but never operated on. In that case though it would still make much more sense to have the class public
but make all the methods within it private
to prevent them being acted on outside your class (or define a public
interface to return and have the private
class implement that).
So the answer seems to be:
It probably shouldn't be valid, but as it doesn't do any harm it has never been blocked.
There is a good answer here on a similar subject: