import java.*;
Why cannot I do this importing ?? Instead of importing the all class in a particular sub-package of the package \'java\' , I tried t
As you can read in this link on Oracle docs, under the heading Apparent Hierarchies of Packages:
At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a
java.awt
package, ajava.awt.color
package, ajava.awt.font
package, and many others that begin withjava.awt
. However, thejava.awt.color
package, thejava.awt.font
package, and otherjava.awt.xxxx
packages are not included in thejava.awt
package. The prefixjava.awt
(the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.
There is no such thing as sub-package in java.
java.util.stream
is not a sub-pacakge of java.util
.
Therefore import java.util.*
doesn't import the classes of java.util.stream
.
To import all the built in classes, you have to import them one package at a time. It's a better practice, though, to only import the classes that you actually need.
Because import some.example.Type;
is only to import types not the packages. import some.example.*;
means you're importing all the Types contained inside some.example
package not the other packages inside it.
This is because import means the code of that file will be available for your program at run time and package itself doesn't contain any code. It contains files which have the code.
That's why you can't import all the built-in code in a single import statement. At max you can import in a single statement is all the code available in different files within a package and you know the way import some.example.*;
Using a wildcard when importing classes may clutter your classes namespace so if you'll have a class named ClassA
in more then one import (e.g. import com.example1.*
and import com.example2.*
where ClassA
is defined in both and you need only the implementation in com.example1
) you will have a conflict so only import what you really need to use.
Most IDEs allows you to easily organize your imports so only the classes that you really need to use will be imported
It is not like what you think, consider when you want to use ChannelHandler
interface you could do either import io.netty.channel.*;
or import io.netty.channel.ChannelHandler;
but you cant use import io.netty.*;
and that why you cant import java.*;
You can import java.util.* it work fine but when you import specific class instead of all class it take less time in importing but if you are importing too many classes from same package you can import all classes using package.* and it takes less time for jvm to fetch instead of taking one by one.
By convention you can use import package.* if you are using too many classes from same package.