Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-public top level class in Java

Tags:

java

What's the reason of making top-level class non-public in Java?

Let's say we have Foo.java, there could be

class Foo {
}

or

public class Foo {
}

I understand that there will be some class - visibility issues with the former example (probably it won't be visible from other packages). But anyway, are there any reasons why someone may want to do as in the first code sample?

UPD: What cons I see in the former solution: nobody cares that it's non-public. That class can be simply extended by some other public class in the same package later, then, non-public part of the class may bring you visibility/access issues.

like image 246
dhblah Avatar asked Aug 09 '11 13:08

dhblah


1 Answers

Here is an example. No one needs to know about existence of our ConcreteDocument.

DocumentIF.java

public interface DocumentIF {
}

ConcreteDocument.java

class ConcreteDocument implements DocumentIF {
}

DocumentFactory.java

public class DocumentFactory {
    public DocumentIF createDocument() {
        return new ConcreteDocument();
    }
}
like image 125
n0rm1e Avatar answered Nov 01 '22 18:11

n0rm1e