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

后端 未结 17 1609
梦谈多话
梦谈多话 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:42

    please see my article Import on Demand is Evil

    In short, the biggest problem is that your code can break when a class is added to a package you import. For example:

    import java.awt.*;
    import java.util.*;
    
    // ...
    
    List list;
    

    In Java 1.1, this was fine; List was found in java.awt and there was no conflict.

    Now suppose you check in your perfectly working code, and a year later someone else brings it out to edit it, and is using Java 1.2.

    Java 1.2 added an interface named List to java.util. BOOM! Conflict. The perfectly working code no longer works.

    This is an EVIL language feature. There is NO reason that code should stop compiling just because a type is added to a package...

    In addition, it makes it difficult for a reader to determine which "Foo" you're using.

提交回复
热议问题