Thursday, March 12, 2009

What are the practical benefits, if any, of importing a specific class rather

Question :What are the practical benefits, if any, of importing a specific class rather
than an entire package (e.g. import java.net.* versus import
java.net.Socket)? (CoreJava)

Answer :It makes no difference in the generated class files since only the classes
that are actually used are referenced by the generated class file. There is
another practical benefit to importing single classes, and this arises when
two (or more) packages have classes with the same name. Take
java.util.Timer and javax.swing.Timer, for example. If I import java.util.*
and javax.swing.* and then try to use "Timer", I get an error while
compiling (the class name is ambiguous between both packages). Let's say
what you really wanted was the javax.swing.Timer class, and the only
classes you plan on using in java.util are Collection and HashMap. In this
case, some people will prefer to import java.util.Collection and import
java.util.HashMap instead of importing java.util.*. This will now allow them
to use Timer, Collection, HashMap, and other javax.swing classes without
using fully qualified class names in.

No comments: