Robert Munteanu
Robert Munteanu

Reputation: 68268

Class resides in different directory than what the package specifies - how come?

The following statements seem to disturbingly function:

robert@neghvar:~/tmp> cat org/foo/Bar.java 
public class Bar {

}

robert@neghvar:~/tmp> javac org/foo/Bar.java 
robert@neghvar:~/tmp> javap org.foo.Bar
Compiled from "Bar.java"
public class org.something.Bar extends java.lang.Object{
    public org.something.Bar();
}

Although the Bar class file is in the org/foo directory and declares the org.something package, the compiler does not complain. I was under the impression that java mandated a directory hierarchy which follows the package name. Was I mistaken? If so, what are the consequences of mixing up package names?

Upvotes: 4

Views: 986

Answers (2)

kaliatech
kaliatech

Reputation: 17867

The source directory structure is not required to follow package naming (even though it almost always does by convention.)

I think the Sun/Oracle javac,javap,java,etc. tools (and all other Java implementations that I know of) are what mandate the subdirectory per package name component rule (along with the default class loaders). I couldn't find anything authoritative, but it doesn't seem to be a requirement of the Java language specification:

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272297

It's purely convention. The compiler will use the package names.

Having said that, it's not usually a good idea to break with this convention. It'll cause inconsistency (the classes generated will be in directories following the package) and some confusion!

Upvotes: 2

Related Questions