I have some questions about the Java compiler

I have some questions about the Java compiler.

My current directory is as follows.

├── Hoge.java ├── Sample.class ├── Sample.java ├── pattern01 │  └── com │  └── cat │  └── Hoge.class └── pattern02 └── com └── cat └── Hoge.class 

----- Sample.java -----

 import com.cat.Hoge; public class Sample { public static void main(String[] args) { System.out.println("hello!"); Hoge h = new Hoge(); h.call(); } } 

----- pattern01 -----

 package com.cat; public class Hoge { public void call() { System.out.println("com.cat"); System.out.println("pattern01"); } } 

----- pattern02 -----

 package com.cat; public class Hoge { public void call() { System.out.println("com.cat"); System.out.println("pattern02"); } } 

I compiled Sample.java as follows.

 $ javac -cp pattern01 Sample.java 

And I execute it like this.

 $ java -cp .:pattern01 Sample hello! com.cat pattern01 $ java -cp .:pattern02 Sample hello! com.cat pattern02 

Both patterns01 and pattern02 usually complete.

But I compiled with pattern01. Why does the program usually end with pattern02?

What does the compiler check? Does the compiler check only the class name?

+6
source share
1 answer

Classes are allowed at runtime. You compiled your client class (sample) with the version of the Hoge class in the classpath and ran it with a different version of the class. Since the class is still compatible (same package, same name, same method signature), everything is going well.

That allows you to compile classes with a specific version of the library (or JDK), but still run it with a different version of the same library (or JDK). If this were not possible, it would be a nightmare to create reusable libraries, since each library must be compiled against each version of the JDK and each version of each dependent library.

+8
source

Source: https://habr.com/ru/post/944346/


All Articles