Joe Boman wrote:1. Why does the Top class have visibility when Top and Bottom2 are in the same file (Bottom2.java)?
2. Why does the Top class have visibility when Top is in a different file? (The original question)
Campbell Ritchie wrote:The visibility has nothing to do which file the code is in.
Yes. It’s all in the Java Language Specification. It is really easy to read. That last statement was a dreadful lieJoe Boman wrote:Hello again Campbell,
. . . I now realize unnamed package is an actual concept in Java. In the interim I had taken this question offline and learned the unnamed package is also known as the default package. Do I understand that correctly?
Where did you find that? Not quite sure what it means. All top‑level classes in an unnamed package have package‑private (=default) access or public access, so they are all visible to one another. Of course you can have a different unnamed package in a different folder, whose classes are not observable to the other unnamed package. I do not know whether you can change the classpath to make those classes observable.Along the way I found someone who wrote the following:
, classes with no package declarations are implicitly part of an "unnamed package", often also called "default package". However, since it's not possible to import classes from an unnamed package and since the language spec explicitly allows implementations to have different rules about whether and how classes in unnamed packages are visible to each other, it's generally a good idea to put all classes in named packages except for experimental code.
Campbell Ritchie wrote:Of course you can have a different unnamed package in a different folder, whose classes are not observable to the other unnamed package.
The unnamed package inside pack2 folder appears not to be able to “see” the unnamed package in the pack1 folder.mkdir pack1
[campbell@localhost java]$ mkdir pack2
[campbell@localhost java]$ gedit pack1/Foo.java pack2/Bar.java
[campbell@localhost java]$ javac pack2/Bar.java
pack2/Bar.java:3: error: cannot find symbol
Foo f = new Foo();
^
symbol: class Foo
location: class Bar
pack2/Bar.java:3: error: cannot find symbol
Foo f = new Foo();
^
symbol: class Foo
location: class Bar
2 errors
If you add pack1 to the classpathEarlier, I wrote:I do not know whether you can change the classpath to make those classes observable.
… it compiles first time. So you appear to be correct, Jeff, and I was mistaken.[campbell@localhost java]$ javac -cp pack1:. pack2/Bar.java
If you're gonna buy things, buy this thing and I get a fat kickback:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
|