08 – Importing

Placing your code into different packages is no good if you can’t access the code from other across those packages. To do so we introduce the idea of the import. For example if we take our class representing a human and place it into yourinitials.beings package but we want to use it with a program in the yourinitials.app package, all you would have to do is import either the class you need or the entire package that class is in. This is how you would do it from a class that’s in your app package.


package yourinitials.app;

import yourinitials.beings.Human;

public class TestHumans {
  // ...

or

package yourinitials.app;

import yourinitials.beings.*;

public class TestHumans {
  // ...

Here we demonstrate two methods for importing the needed class. The first explicitly names the class and the second grabs everything from the package and imports it. Because this happens at compile time there is no real performance penalty for using either method. The only danger is that you might import a class into your namespace that has the same name as a class already in your namespace. You would have to fully qualify which you meant when you tried to create a variable or instance of that class.


package yourinitials.app;

import yourinitials.beings.*; // Contains a Cat class.
import bobs.barnyardanimals.*; // Also has a Cat class!

public class TestCats {
  public static void main(String[] args) {
    // Cat c = new Cat(“Spot”); // Ambiguous! Won't compile!
    bobs.barnyardanimals.Cat c;
    c = new bobs.barnyardanimals.Cat(“Fluffy”);

As you can see, this doesn’t represent a real problem for us, it just forces us to use a more verbose means of identifying the class we want to use.

Importing Exercise

Create a beings package underneath the yourinitials package. Put your Human class from your Static vs. Instance exercise inside of this new package. You’ll need to alter it so that it is valid in the new package. Create a TestHuman class in your app package. Have it create a instance of Human and set it’s age. Then get it’s age back out of the class and print out the age. Of course you’ll need to import your Human class for this exercise to work.