java -version
java version "14" 2020-03-17
Java(TM) SE Runtime Environment (build 14+36-1461)
Java HotSpot(TM) 64-Bit Server VM (build 14+36-1461, mixed mode, sharing)
package reusing; import static net.mindview.util.Print.*; class Cleanser { private String s = "Cleanser"; public void append(String a) { s += a; } public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } public String toString() { return s; } public static void main(String[] args) { Cleanser x = new Cleanser(); x.dilute(); x.apply(); x.scrub(); print(x); } } public class Detergent extends Cleanser { private Cleanser cl = new Cleanser(); // Change a method: public void append(String a){ cl.append(a); } public void dilute(){ cl.dilute(); } public void apply(){ cl.apply(); } public void scrub(){ cl.scrub(); } // Test the new class: public static void main(String[] args) { Detergent x = new Detergent(); x.dilute(); x.apply(); x.scrub(); print(x); print("Testing base class:"); Cleanser.main(args); } }
Attention, please, to the first line (where "package reusing;");
Then.
Case 1.
michael@michael:~/Downloads/thinking_in_java/TIJ4-code-master/examples/reusing$ java -cp /home/michael/Downloads/thinking_in_java/TIJ4-code-master/examples:. Detergent.java Cleanser dilute() apply() scrub()
A paradox.
Working. But I think it shouldn't.
Case 2.
michael@michael:~/Downloads/thinking_in_java/TIJ4-code-master/examples/reusing$ javac -cp /home/michael/Downloads/thinking_in_java/TIJ4-code-master/examples:. Detergent.java michael@michael:~/Downloads/thinking_in_java/TIJ4-code-master/examples/reusing$ java -cp /home/michael/Downloads/thinking_in_java/TIJ4-code-master/examples:. Detergent Error: Could not find or load main class Detergent Caused by: java.lang.NoClassDefFoundError: reusing/Detergent (wrong name: Detergent)
Well. This is expected. If I comment out that abovementioned line, the code will work and compile.
Could you tell me why the code worked in case 1?