Home > Back-end >  Which import should be considered?
Which import should be considered?

Time:12-15

Consider the following code snippet.

package spoon;

import rx.Observable;
import java.util.*;

public class Test {
    public void test() {
        Observable o = new Observable();
    }
}

This code compiles well with Java 11 even though I thought it should not. Observable is also a java class in java.util and I do not understand how the compiler knows whether to use Observable from java.util or my custom package rx.

Note that java.util.Observable was deprecated in Java 9, however, I don't think so it should have any effect on imports.

CodePudding user response:

The single name import wins over the wildcard (called "import-on-demand" by the standard).

To cite chapter and verse:

https://docs.oracle.com/javase/specs/jls/se11/html/jls-7.html#jls-7.5.2

"The declaration might be shadowed by a single-type-import declaration of a type whose simple name is..."

https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.4.1

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

CodePudding user response:

**import rx.Observable;**

This one will be considered by the compiler because you have mentioned the specific path. but you want to use from import java.util.* you have to use like this java.util.Observable o = new java.util.Observable();

CodePudding user response:

Just tried it, and basically, the Single-Type-Import declaration is overwriting the types from the Type-On-Demand (.*;) declaration.

Example Type-on-Demand conflict - compile-time error:

import java.sql.*;
import java.util.*;

public class Test {
     Date birthDate; // Date is ambiguous (!!)
}

Example Single-Type-Import conflict - compile-time error:

import java.sql.Date;
import java.util.Date;  // Date already defined in single-type import (!!)

public class Test {
     Date birthDate;
}

Example Single-Type-Import / Type-On-Demand - compiles:

import java.sql.Date;
import java.util.*; 

public class Test {
     Date birthDate;    // resolves to java.sql.Date
}

Example Type-On-Demand / Single-Type-Import - compiles:

import java.sql.*;
import java.util.Date; 

public class Test {
     Date birthDate;    // resolves to java.util.Date
}

Which is described in the language documentation (just found it):

the (type-on-demand) declaration might be shadowed by a single-type-import declaration

7.5.2. Type-Import-on-Demand Declarations

https://docs.oracle.com/javase/specs/jls/se11/html/jls-7.html#jls-7.5

The case of naming conflict on that level is not described (at least I wasn't able to find it). Therefore just can give the answer by "try-and-error".

  •  Tags:  
  • java
  • Related