Reputation: 382
I just want to output current and I wrote
import java.util.*;
at beginning, and
System.out.println(new Date());
in the main part.
But what I got was something like this:
Date@124bbbf
When I change the import to import java.util.Date;
the code works perfectly, why?
====================================
The problem was, OK, my source file was "Date.java", that's the cause.
Well, it is all my fault, I confused everybody around ;P
And thanks to everyone below. It's really NICE OF YOU ;)
Upvotes: 9
Views: 131527
Reputation: 7368
The toString()
implementation of java.util.Date
does not depend on the way the class is imported. It always returns a nice formatted date.
The toString()
you see comes from another class.
Specific import have precedence over wildcard imports.
in this case
import other.Date
import java.util.*
new Date();
refers to other.Date
and not java.util.Date
.
The odd thing is that
import other.*
import java.util.*
Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date
and java.util.Date
matches.
Upvotes: 6
Reputation: 27486
but what I got is something like this: Date@124bbbf
while I change the import to: import java.util.Date;
the code works perfectly, why?
What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.
Upvotes: 0
Reputation: 83619
You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.
Or better, try to avoid naming your classes "Date".
Upvotes: 13
Reputation: 2564
import java.util.*;
imports everything within java.util including the Date class.
import java.util.Date;
just imports the Date class.
Doing either of these could not make any difference.
Upvotes: 4
Reputation: 31903
Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.
Upvotes: 2