Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A wildcard is said to import all classes in a package. "It doesn't import child packages, fields, or methods." What does this mean?

Tags:

java

java-8

In the Sybex book, OCA Oracle Certified Associate Java SE 8 Programmer I - Study Guide, page 10 of Chapter 1 states the following:

The * is a wildcard that matches all classes in the package. Every class in the java.util package is available to this program when Java compiles it. It doesn’t import child packages, fields, or methods; it imports only classes. (Okay, it’s only classes for now, but there’s a special type of import called the “static import” that imports other types. You’ll learn more about that in Chapter 4.)

It was my naive understanding that since a class contains members (fields and methods), it is implied that those are imported, as well. However, according to the author of this book, it appears that the situation is more caveated.

If you are importing a class, and you don't have access to the members of that class, then what is the point of importing that class?

like image 591
Ebony Maw Avatar asked Dec 19 '25 22:12

Ebony Maw


1 Answers

what is the point of importing that class?

Imagine that you do not import classes inside java.util. If you want to create a Map you type:

java.util.Map<String, Integer> myMap = new java.util.HashMap<>();

If you import the class in that package like import java.util.*;:

Map<String, Integer> myMap = new HashMap<>();

If you are importing a class, and you don't have access to the members of that class

Imports do nothing with access, they are all about readability and convenience. You don't have to type that much and the second declaration is much more readable, but you can use the same methods of myMap in both cases.


The static import that the book mentions (from the doc):

The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

A good example for static import is the usage of Mockito in unit tests. Without any imports you can verify some behavior like:

org.mockito.Mockito.verify(mock, org.mockito.Mockito.never()).someMethod();

If you use normal import import org.mockito.Mockito;:

Mockito.verify(mock, Mockito.never()).someMethod();

and with static import import static org.mockito.Mockito.*; you can type

verify(mock, never()).someMethod();

Here the verify and never static methods can be used even without specifying their class (Mockito).

like image 140
DVarga Avatar answered Dec 22 '25 11:12

DVarga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!