I have a doubt in import statement. Code snippet for Bigger.java and Bigger1.java is given below:
Line 1 gives me a compiler error saying "Cannot access Bigger. class file contains wrong class: com.path.Bigger" . My directory structure is c:/Project/com/path.
Bigger.java is in Project/com/path/Bigger.java and Bigger1.java is in Project/Bigger1.java. I have the class file of Bigger.java under Project/com/path/Bigger.class directory and under Project/Bigger.class directory.
Please clarify my doubt why Bigger1.java cannot access Bigger.java when I use import com.path.*;. But import com.path.Bigger; doesnt give me any compiler error.
Joined: Feb 17, 2008
please help me with this topic. I am not able to move to the next topic.
Originally posted by Srividhya Kiran: ...I have the class file of Bigger.java under Project/com/path/Bigger.class directory and under Project/Bigger.class directory...
That's the problem. You have the class file in 2 places. Bigger is part of the package com.path, so the class belongs under the directory com/path. The copy under the Project directory is incorrect because of the package declaration.
When you use the "wildcard" import on demand, import com.path.*; Java evidentially tries to resolve the name "Bigger" by looking in the current directory first. This is where it finds your second copy of Bigger.class. This is wrong, because the qualified class name is actually "com.path.Bigger," which belongs under the com/path directory.
On the other hand, when you use import com.path.Bigger, Java evidentially resolves the name "Bigger" by finding the correct class file under com/path before it tries looking in the current directory.
If you remove the incorrect file Bigger.class from your Project directory, then you should be able to use either type of import statement.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
When you declare a package, the qualified name of the class changes. The qualified name of this class is com.path.Bigger, and this is in the directory "Project." Invoke it from the Project directory as...
Originally posted by Srividhya Kiran: ... So we cant run Bigger under path directory??? ...
Keep in mind that Java classes are identified by their qualified names. The Bigger class is in the package com.path, so its qualified class name is "com.path.Bigger" which is under the "Project" directory.
There is no class identified as "Bigger" under the "path" directory. (Yes, there is a .class file there, but that is not how Java identifies classes in packages.)
You could run this from the "path" directory, but you would still need to use the qualified name, and you would need to specify a classpath pointing to the "Project" directory so that Java can find "com.path.Bigger." One way to do this would be to use ".." to go up a level...
C:/Project/com/path>java -cp ../../ com.path.Bigger [ April 09, 2008: Message edited by: marc weber ]