简体   繁体   中英

How do I import packages in Java?

I have a "Sprites" folder with some class files and a "Launcher" folder with some class files. I tried the following code for import:

package Sprites;

and it lead to the following

hw9\Launcher>javac *.java
TowerDefense.java:2: error: class, interface, or enum expected
package Sprites;
^
1 error

Am I doing this incorrectly? My Sprites and Launcher are in the hw9 directory, so I assumed it would work. A picture for clarification: 在此处输入图片说明

You can use a wildcard import to import all classes within the immediate directory:

import Sprites.*;

This opposed to something like:

import Sprites.Class1;
import Sprites.Class2;
import Sprites.Class3;
...

Generally, wildcard imports can produce conflicts and errors (for example java.awt.List and java.util.List ), so usually better to avoid them.

Packages should also be lower-cased.

The error is due to syntax, usually when you see something like ...expected that is syntax error indicator.

In the class in your launcher package, include the import statements for the classes which are being referred to.

It should look something like the following:

package the.name.of.your.package;
import Spirites.NameOfclass; //quialify the import parth as is
class YourLauncherClass{ 
//class definition 
}

Also make sure that semicolons aren't missing at the end of import and package. Hope that helps.

Best practice is to import the specific class you require rather than importing the complete package.

import Spirites.NameOfclassRequired; 
class YourClass{ 
//class definition 
}

If you are using eclipse you can do that using CTRL+SHIFT+O When you do that eclipse imports the specific class you require. For an instance if you using an ArrayList rather than importing java.util.*; it will import java.util.ArrayList;

If you need multiple classes from a package then for sure you can import the entire package

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM