Home
Java
package Example (import Keyword)
This page was last reviewed on Sep 24, 2023.
Dot Net Perls
Package, import. A package contains Java code. It has classes, methods, and other forms of data. We import a package to use it in our program.
To begin, please create a new Java package. Call it something like testPackage and then place a public method in the class. The file declares itself as a package with the package keyword.
Code example. Here we see our testPackage package. It contains a class called Test and a printName method. These projects are in the same directory in Eclipse.
Detail In Eclipse we specify the default package. We can then import other packages with the import keyword into this.
Note We do not need to use the "import" keyword. We can specify a type like testPackage.Test but this is hard to type.
package testPackage; public class Test { public void printName() { // This method is in the Test class in testPackage. System.out.println("Dot Net Perls"); } }
import testPackage.Test; public class Program { public static void main(String[] args) { // Create new instance of Test from testPackage. Test test = new Test(); // Call method. test.printName(); } }
Dot Net Perls
Star. With a star, we can import all types in a certain package. Consider the java.util.function package. We can import all its classes with a star directive.
Lambda
import java.util.function.*;
Package and import. We created a package and imported it into the default package. Importing a package simply makes it easier to access—we can use the "Test" class directly.
With the import keyword, we can use classes like ArrayList with simpler syntax. For ArrayList we import java.util.ArrayList. This makes programs easier to read.
ArrayList
Modularity is a key part of Java programming. Object-oriented programming is about decomposing programs into small parts that can be reused. Packages are meant to be used again and again.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.