Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't Java have "deep" wildcard import? [duplicate]

Why doesn't import one.two.* include import one.two.three.MyClass? Shouldn't Java have something like import one.two.**? Or is there any reason (other than they just didn't do, not that they couldn't do it)?

Thanks

like image 812
One Two Three Avatar asked Dec 13 '13 21:12

One Two Three


People also ask

Are wildcard imports bad Java?

Using wildcard imports in Java would not affect runtime performance of a Java program at all, but compile-time performance may be affected a little.

What is the reasoning to use a specific import instead of a wildcard import?

With specific imports, the class must exist in a package. However, with wildcard imports, particular classes don't need to exist in the package.

What are specific and wildcard imports?

Specific imports are hard dependencies, whereas wildcard imports are not. If you specifically import a class, then that class must exist. But if you import a package with a wildcard, no particular classes need to exist. The import statement simply adds the package to the search path when hunting for names.


2 Answers

Java does not treat packages as truly subclassing each other; while java.util and java.util.concurrency might look like the second is somehow part of the first, they are treated as entirely independent and the dot is mostly there for neatness.

This means you don't need to be afraid of naming your class or interface the same as another one declared in some super- or sub-package on a later date, and it also means you should really just write a couple extra lines of imports.

The reasons behind this decision, as Peter Lawrey explained, stem from Java's general lean towards simplicity. Best practice is often to never use import wildcards at all anyway.

like image 76
Mumbleskates Avatar answered Oct 23 '22 22:10

Mumbleskates


Java treats each package as independent. For example, package local don't extend to any "sub" packages. I suspect using the hierarchy in a meaningful way would be valuable but Java's design was to make everything as simple as possible.

Or is there any reason (other than they just didn't do, not that they couldn't do it)?

The problem is backward compatibility which might break older programs. I suspect this is solvable.

In truth, most IDEs manage your imports for you and I don't even look at my imports any more. Certainly avoiding import * is preferable so that all classes are explicitly imported.

like image 4
Peter Lawrey Avatar answered Oct 23 '22 22:10

Peter Lawrey