Implicit import vs Explicit import in java
Well, First make a choice what will be the answer most of you must have thought already it's a compile time error because of ambiguity. Yes, but no answer is similar to it. After compiling the code we will get this below error.
Demo.java:2: error: a type with the same simple name is already defined by the single-type-import of Date import java.sql.Date; ^ 1 error
But, this error is different to ambiguous error that we will talk about it later. All this error has to say that is
The class you want to import java.sql.Date is of a type with the same name which is already defined above. So you cannot import same type of classes. Compiler will give this error on the second line itself.
Hope You Understand it! Lets Take one more example Little bit different
Example 2:
GUESS THE ANSWER FIRST.
Now in this example we don't get error on import statement. We will get the error in main where we are trying to create object of Date. But now Date class is present in both java.util & java.sql so compiler can't decide which class object he have to create so he will give us a compiler time error saying.
Demo.java:5: error: reference to Date is ambiguous Date date= new Date(); ^ both class java.sql.Date in java.sql and class java.util.Date in java.util match
So now we will get the ambiguity error. Hope this is all clear now.
But how do you resolve it that question is still there?
There are two types of import statement in java
- Implicit import (java.util.*)
- Explicit import (java.util.Date)
So java will give the preference of import according to
- Explicit import (java.util.Date)
- Classes present in current working directory
- Implicit import (java.util.*)
Here is the Solution you are waiting for
In this case java.util.Date class object will be created Make the class import statement explicit which object you want to create.
But it's better programming practice to always use explicit class import
You can also use Fully Qualified Name for resolving the issue.
THANK YOU