Shan
Shan

Reputation: 381

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: enter image description here

Upvotes: 0

Views: 108

Answers (3)

techPackets
techPackets

Reputation: 4516

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

Upvotes: 0

Nirmal
Nirmal

Reputation: 1259

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.

Upvotes: 0

Obicere
Obicere

Reputation: 3019

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.

Upvotes: 2

Related Questions