开发者

What's the difference between import java.util.*; and import java.util.Date; ?

开发者 https://www.devze.com 2022-12-10 08:13 出处:网络
I just want to output current and I wrote import java.util.*; at beginning, and System.ou开发者_StackOverflowt.println(new Date());

I just want to output current and I wrote

import java.util.*;

at beginning, and

System.ou开发者_StackOverflowt.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 ;)


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".


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消