Lab 06
In this lab we'll briefly revise the scope of packages, how to bridge them with imports, and how things relate to the classpath.
Imports and packages
- Imports are required whenever you cross package boundaries.
- However, there's on exception: classes from the standard-library do not need to be imported.
Your turn
- Create a new project with at least 2 packages,
aandb.- Create a new class in each package.
- Attempt to create a
newclass of packagebform your class in packagea.
- Verify an import is required.
- Verify what happens if you remove the import. What is the compiler error message ?
- Create a
new String, anew LinkedList, and printMath.PIfrom one of your classes.- How many import statements are needed ? Why do you not need an import for each of the used classes ?
Classpath
By default, the compiler and JVM only "know" what is on the classpath. That is, you cannot import artifacts outside the classpath, and you cannot run software depending on artifacts outside the classpath.
In this exercise you'll briefly train how to integrate a library class without copy pasting its source code into your project.
Your turn
- Download this sample library: amazinglib.jar
- Save the file somewhere outside your project.
- Inspect the jar file content (you can rename the file ending to
zipand unpack the file).
- The library contains only one interface
AmazingInterface, with a single methodvoid doSomethingAmazing()- You now want to
implementthe provided interface. - Create a new class
AmazingImplementation:
- You now want to
import amazing.AmazingInterface;
public class AmazingImplementation implements AmazingInterface {
public void doSomethingAmazing() {
System.out.println("Wowser !");
}
}
- Create a launcher class, invoking the
doSomethingAmazingmethod - Now see if you can compile and run your application. Reminder:
- To compile, use the
-cp .../.../amazinglib.jarargument, where.../.../refers to the location on disk. - To run, use the
-cp .../.../amazinglib.jar:.argument, where.../.../refers to the location on disk, and:.extends the classpath by the classfiles in the current directory.
- To compile, use the
- Verify both steps succeed.