Skip to content

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, a and b.
    • Create a new class in each package.
    • Attempt to create a new class of package b form your class in package a.
  • Verify an import is required.
    • Verify what happens if you remove the import. What is the compiler error message ?
  • Create a new String, a new LinkedList, and print Math.PI from 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 zip and unpack the file).
  • The library contains only one interface AmazingInterface, with a single method void doSomethingAmazing()
    • You now want to implement the provided interface.
    • Create a new class AmazingImplementation:
import amazing.AmazingInterface;

public class AmazingImplementation implements AmazingInterface {

    public void doSomethingAmazing() {
        System.out.println("Wowser !");
    }
}
  • Create a launcher class, invoking the doSomethingAmazing method
  • Now see if you can compile and run your application. Reminder:
    • To compile, use the -cp .../.../amazinglib.jar argument, 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.
  • Verify both steps succeed.