Examples of Package Imports
Here are some examples of how to import packages in Java code:
Importing a Specific Class
To import a specific class from a package, you can use the import
statement followed by the fully qualified class name:
import com.example.MyClass;
public class MyApp {
public static void main(String[] args) {
MyClass myObject = new MyClass();
// Use methods and fields from MyClass
}
}
Importing an Entire Package
To import all the classes and interfaces from a package, you can use the wildcard *
character:
import com.example.*;
public class MyApp {
public static void main(String[] args) {
MyClass myObject = new MyClass();
AnotherClass anotherObject = new AnotherClass();
// Use methods and fields from MyClass and AnotherClass
}
}
Importing Static Members
You can also import static methods and fields from a class using the import static
statement:
import static com.example.MyClass.MY_CONSTANT;
import static com.example.MyClass.myStaticMethod;
public class MyApp {
public static void main(String[] args) {
System.out.println(MY_CONSTANT);
myStaticMethod();
}
}
In this example, we import the MY_CONSTANT
field and the myStaticMethod()
method from the MyClass
class, allowing us to use them directly in our code without having to prefix them with the class name.
Importing Nested Classes
You can also import nested classes from a package:
import com.example.OuterClass.InnerClass;
public class MyApp {
public static void main(String[] args) {
InnerClass innerObject = new InnerClass();
// Use methods and fields from InnerClass
}
}
In this example, we import the InnerClass
nested class from the OuterClass
class in the com.example
package.
By understanding these examples, you can effectively import the packages, classes, and static members you need in your Java code, making it more readable and maintainable.