Why is using a wild card with a Java import statement bad?

后端 未结 17 1534
梦谈多话
梦谈多话 2020-11-21 13:07

It is much more convenient and cleaner to use a single statement like

import java.awt.*;

than to import a bunch of individual classes

相关标签:
17条回答
  • 2020-11-21 13:57

    Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.

    0 讨论(0)
  • 2020-11-21 13:58

    The most important one is that importing java.awt.* can make your program incompatible with a future Java version:

    Suppose that you have a class named "ABC", you're using JDK 8 and you import java.util.*. Now, suppose that Java 9 comes out, and it has a new class in package java.util that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class in java.awt.

    You won't have that problem when you import only those classes explicitly from java.awt that you actually use.

    Resources:

    Java Imports

    0 讨论(0)
  • 2020-11-21 13:58

    For the record: When you add an import, you are also indicating your dependencies.

    You could see quickly what are the dependencies of files (excluding classes of the same namespace).

    0 讨论(0)
  • 2020-11-21 14:00

    It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:

    import java.util.*;
    import java.awt.*;
    
    ...
    List blah; // Ambiguous, needs to be qualified.
    

    It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.

    0 讨论(0)
  • 2020-11-21 14:00

    I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)

    0 讨论(0)
提交回复
热议问题