Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Packaging problem

 
C WL
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have some problem about the package statement. For example, in the following three classes with definition:
=================================================
package chapter1;
public class CharStack {
...
} // End of class CharStack
=================================================
package chapter1;
public class PrintableCharStack extends CharStack {
...
} // End of class PrintableStack
=================================================
package chapter2;
import chapter1.*;
public class Client {

public static void main(String[] args) {
PrintableCharStack a = new PrintableCharStack(3);
a.push('H');
a.push('i');
a.push('!');
a.printStackElements();
}

} // End of class Client
=================================================
If I omit for package statement from the class Client, it will fail to compile with error "file does not contain class PrintableCharStack" even I import the package chapter1. However, if I add the package statement (package chapter2), it will compile and run correctly.
My question is why such an error would occur. Any impact on the package statement from the above case.
 
Tim B.
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi C WL,
It is correct that the compiler fails to compile when you omit the package statement in the Client object. This because the package statement can be seen as the directory in which the file is stored.
So when you omit the package statement in the Client file, it thinks the directory of the file is actually the root directory. Importing chapter1.* will therefore look for a directory 'chapter1' in the same directory (/chapter1/chapter2/*) as the Client.java file. When you include the package statement, it knows the actual path to the file is '/chapter2/Client.java' and therefore will look for the 'chapter1' directory one level lower than the Client.java source file is in.
Hopefully you are able to follow the above explanation. If not, feel free to post a question for more information and I'll try to be a bit more specific then.
Greetings,
Tim
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic