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 ;)
The
toString()
implementation ofjava.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
refers to
other.Date
and notjava.util.Date
.The odd thing is that
Should give you a compiler error stating that the reference to Date is ambiguous because both
other.Date
andjava.util.Date
matches.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".
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.
imports everything within java.util including the Date class.
just imports the Date class.
Doing either of these could not make any difference.
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.