importing classes using wildcards

后端 未结 5 1045
太阳男子
太阳男子 2021-01-06 02:18

If I say:

import java.awt.event.ActionListener;

I get the ActionListener Class. If I say:

import java.awt.event.*;
<         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 03:02

    Remember that the import statement is just for convenience. It is there to make it possible for you to use the short name of a class rather than the fully qualified name.

    The package name structure in Java corresponds to a directory structure. So you can think of it as a directory named java and in that directory there are several other directories such as awt and io etc.

    When you say

    import java.awt.*;
    

    you are basically saying that you want to use the short name for all the classes in the directory named awt inside the directory named java. So if you use a class name in your code like this:

       List mylist;
    

    Then the compiler will attempt to find either a class named List in the current package or a class named java.awt.List.

    So if you have a directory inside the awt directory called event and you have a class named ActionEvent in that directory, the fully qualified name is:

      java.awt.event.ActionEvent
    

    and the import statement above does not help. Hence the reason for needing another import statement

      import java.awt.event.*;
    

    Now, if you use the class ActionEvent the compiler looks for a class named ActionEvent in the current directory, or java.awt.ActionEvent or java.awt.event.ActionEvent until it finds one.

提交回复
热议问题