The situation is as follows. jdk1.6.0_25 In the directory ./test/p program Cl1.java In the CLASSPATH, the path to ./test/p is registered. CLASSPATH =; C: \ Documents and Settings \ avp \ java \ src
package test.p; public class Cl1 { public Cl1() { System.out.println("Cl1 ()"); } public static void priTest() { System.out.println("Cl1 test"); } public static void main (String [] av) { System.out.println("Cli main test"); } }
And in the directory ./test program Tcl1.java
import test.p.*; public class Tcl1 { public static void main (String [] av) { Cl1 c = new Cl1(); c.priTest(); } }
Execute commands
c:/Documents and Settings/avp/java/src/test/p $ javac Cl1.java c:/Documents and Settings/avp/java/src/test/p $ cd .. c:/Documents and Settings/avp/java/src/test $ javac Tcl1.java c:/Documents and Settings/avp/java/src/test $ java Tcl1 Cl1 () Cl1 test c:/Documents and Settings/avp/java/src/test $ c:/Documents and Settings/avp/java/src/test $
Bye ok
Copy Tcl1.java to ./test/p and try to compile it. Question number 1
c:/Documents and Settings/avp/java/src/test $ cp Tcl1.java p/ c:/Documents and Settings/avp/java/src/test $ cd p c:/Documents and Settings/avp/java/src/test/p $ javac Tcl1.java Tcl1.java:7: cannot access Cl1 bad class file: .\Cl1.class class file contains wrong class: test.p.Cl1 Please remove or make sure it appears in the correct subdirectory of the classpath. Cl1 c = new Cl1(); ^ 1 error c:/Documents and Settings/avp/java/src/test/p $ c:/Documents and Settings/avp/java/src/test/p $
Attempt to perform Cl1.class (after all, it has main ()!) Question number 2
c:/Documents and Settings/avp/java/src/test/p $ java Cl1 java.lang.NoClassDefFoundError: Cl1 (wrong name: test/p/Cl1) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) ......... at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: Cl1. Program will exit. Exception in thread "main" c:/Documents and Settings/avp/java/src/test/p $
Naturally, if you comment out the line with the package in Cl1.java, then everything compiles and Cl1 works.
Sorry for the long and probably stupid question, but I read the books (apparently not carefully enough), but I don’t understand why the package and main are incompatible , and why the class with main is not compiled in the same table of contents where the imported classes lie. (However, compiled elsewhere, it runs anywhere).
Or am I doing something elementary wrong?
In the command window of Windows, everything is exactly the same, but I cannot copy-paste from there.