Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java import wildcard not importing everything inside package

I'm writing a Java program that has a button with an action listener:

    JButton button = new JButton("Change");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            label.setText(textField.getText());
        }
    });

At the top of the file, I have these two import statements:

import java.awt.*;
import javax.swing.*;

I know this is terrible practice, I am revising for an exam and it's way easier and quicker to just write that at the top of the page.

I get an error, however, telling me to import java.awt.event.ActionListener

If the event package is inside java.awt and I used the wildcard * to import everything, then why is it not being imported??

like image 245
user2397282 Avatar asked May 16 '26 10:05

user2397282


1 Answers

Here is the definition of type-import-on-demand in the Java Language Specification:

A type-import-on-demand declaration allows all accessible types of a named package or type to be imported as needed.

TypeImportOnDemandDeclaration: import PackageOrTypeName . * ;

It is important to understand the terminology: "all accessible types of a named package" means all the types whose package declaration is specifically the one before the .*.

So, if a class's package is defined like:

package my.pkg.name;

Then it will be available to import my.pkg.name.*, but if a class is defined like:

package my.pkg.name.subname;

Then it will not be available to import my.pkg.name.*, because it does not belong to that package. It specifically belongs to my.pkg.name.subname which is - as far as Java is concerned - a different package.

It is true that Java implementations normally expect the packages to be ordered in a directory hierarchy, so the directory for my.pkg.name.subname is going to be under the directory of my.pkg.name. If you think of it, supposed you wrote

ls my/pkg/name/*

In that directory. It behaves very much the same: it would give you only the files under this directory directly, not the directories further under it. The semantics of type-import-on-demand is pretty much the same (excluding the subname "directory" itself, because it is not a type).

like image 151
RealSkeptic Avatar answered May 17 '26 22:05

RealSkeptic



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!