Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have some questions about Java compiler

I have some questions about Java Compiler.

My current directory is like this.

├── 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 like this.

$ 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 pattern01 and pattern02 are normally ended.

But I compiled with pattern01. Why did program normally end with pattern02?

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

like image 319
Akira Noguchi Avatar asked May 06 '13 06:05

Akira Noguchi


1 Answers

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

That's what allows compiling classes with a given version of a library (or the JDK), but still run it with another version of the same library (or the JDK). If this wasn't possible, it would be a nightmare to build reusable libraries, since every library would have to be compiled against every version of the JDK and every version of every dependant library.

like image 69
JB Nizet Avatar answered Sep 28 '22 10:09

JB Nizet