Static import with same static variable names
Asked Answered
L

1

8

I am doing a static import of members of class Long and Integer:

import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;

Now if I am trying to use this variable MAX_VALUE and print it I will get an error:

import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;

public class StaticImportDemo2 {
    public static void main(String[] args) {
        //Error :: The field MAX_VALUE is ambiguous 
        System.out.println("Print without static import Integer.MAX_VALUE "+MAX_VALUE);
    }
}

This is fine. To remove the error i will have to remove one static import to resolve this ambiguity .

The main issue I am getting is, if I use wildcard * with Integer class static import, the class gets compiled with no errors:

import static java.lang.System.out;
import static java.lang.Integer.*;
import static java.lang.Long.MAX_VALUE;

public class StaticImportDemo2 {
    public static void main(String[] args) {
        System.out.println("Print without static import Integer.MAX_VALUE " + MAX_VALUE);
    }
}

The ambiguity must still exist. Why does this compile with no issues?

Litharge answered 29/5, 2018 at 1:19 Comment(4)
so explicitly imported values take precendanceUtu
Thats something you deduced from the above code but the question is why does this happen ?Litharge
It is written here plus also somewhere is the JLSUtu
Also written is You are advised not use static imports at all, or only in very rare circumstances. - this is a common messageUtu
A
6

Why does this compile with no issues?

Because the Java Language Specification says that it does. See chapter 6 and 7, but particularly from 6.4.1:

A type-import-on-demand declaration never causes any other declaration to be shadowed.

A static-import-on-demand declaration never causes any other declaration to be shadowed.

And that’s probably because it’s very convenient to be able to wildcard-import entire packages, but sometimes you’ll have to resolve conflicts. It would suck (particularly in pre-IDE days) if the only alternative was to explicitly import every item. So specific (non-wildcard) imports were given precedence. That way, you just specify which you mean for the ambiguous items you want to use.

Alienist answered 29/5, 2018 at 2:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.