Jack Ng

Essay

Learning Java, Part 8: Packages and Interfaces

Study notes on declaring and importing packages, the classpath, how access modifiers work across packages, interfaces and implementing them, interface references, constants, extending interfaces, default and static methods, and choosing between an interface and an abstract class. Written entirely by an AI model.

Packages organise classes into named groups and control who can see them. Interfaces describe what a class can do without saying how. Together they are how large Java programs are put together, and the interface versus abstract class question appears in almost every CITS2005 exam.

Packages

A package is a namespace for classes, and it maps onto a folder. The first line of the source file declares it:

// file: cafe/menu/Item.java
package cafe.menu;

public class Item {
    private final String name;
    public Item(String name) { this.name = name; }
    public String name() { return name; }
}
// not run alone: compile it together with Item.java
// file: cafe/App.java
package cafe;

import cafe.menu.Item;        // or: import cafe.menu.*;

public class App {
    public static void main(String[] args) {
        System.out.println(new Item("scone").name());
    }
}

Compile and run from the folder above cafe, using the full name:

javac cafe/menu/Item.java cafe/App.java
java cafe.App
  • The folder structure must match the package name: cafe.menu lives in cafe/menu/.
  • The classpath tells java and javac where package roots are. By default it is the current directory; -cp lib:classes changes it.
  • A file with no package line is in the default package. That is fine for small exercises but cannot be imported from a named package.
  • The convention for real code is a reversed domain name: au.edu.uwa.cits2005.lab3.
  • import only saves typing. Without it, you can always write the full name, java.util.Scanner. java.lang is imported automatically.
  • Two classes with the same simple name in different packages (java.util.List and java.awt.List) can both be used if you write one in full.

Access across packages

Part 6’s table, read again with packages in mind:

same class same package subclass in another package anywhere
private yes
(none) yes yes
protected yes yes yes
public yes yes yes yes

The default (no modifier) is package-private. A top-level class can only be public or package-private. Code in another package can’t see a package-private class at all.

The standard library is packages

Package Contains
java.lang String, Math, System, Object, Thread, wrappers
java.util collections, Scanner, Random, Optional
java.io, java.nio.file streams, files, paths
java.util.concurrent executors, locks, atomic counters
java.time dates and times

Interfaces

An interface is a named set of method signatures. A class that implements it promises to provide those methods. Code can then work with any implementing class through the interface type.

interface Payable {
    int amountCents();                 // implicitly public and abstract
}

class Invoice implements Payable {
    private final int cents;
    Invoice(int cents) { this.cents = cents; }
    public int amountCents() { return cents; }    // must be public
}

class Wage implements Payable {
    private final int hours, rateCents;
    Wage(int hours, int rateCents) { this.hours = hours; this.rateCents = rateCents; }
    public int amountCents() { return hours * rateCents; }
}

public class Payroll {
    static int total(Payable[] items) {
        int sum = 0;
        for (Payable p : items) sum += p.amountCents();
        return sum;
    }
    public static void main(String[] args) {
        Payable[] due = { new Invoice(12000), new Wage(10, 3050) };
        System.out.println(total(due));
    }
}
42500
  • Interface methods are public by default, so the implementing method must be declared public. Leaving it package-private is a compile error (“attempting to assign weaker access privileges”).
  • A class can implement several interfaces: class Tablet implements Camera, Phone. It can extend one class and implement interfaces at the same time: class Hybrid extends Car implements Chargeable.
  • A class that does not implement every method must be declared abstract.
  • You cannot new an interface, but you can declare variables of its type. Those interface references give the same runtime dispatch as superclass references in Part 7.

Constants in interfaces

Any field in an interface is implicitly public static final, which makes it a constant. Older code used interfaces just to hold constants; today an enum (Part 12) or a final class of constants is clearer.

Extending interfaces

An interface can extend one or more others. A class implementing the child must provide every method of the whole family:

interface Readable { String read(); }
interface Writable { void write(String s); }
interface Store extends Readable, Writable { void clear(); }

Default and static methods

Since Java 8, an interface may contain:

  • default methods, with a body, which implementing classes inherit and may override. They let a library add methods to an interface without breaking every class that already implements it.
  • static methods, called through the interface name.
  • (Since Java 9) private methods, helpers for the default methods.
interface Greeter {
    String name();
    default String greet() { return "Hello, " + name() + "!"; }
    static Greeter of(String n) { return () -> n; }   // lambda: Part 14
}

class Formal implements Greeter {
    public String name() { return "Ms Ng"; }
    @Override public String greet() { return "Good morning, " + name() + "."; }
}

public class Greeters {
    public static void main(String[] args) {
        System.out.println(Greeter.of("Omar").greet());
        System.out.println(new Formal().greet());
    }
}
Hello, Omar!
Good morning, Ms Ng.

When two defaults collide

If a class implements two interfaces with the same default method, it must override that method, or the class does not compile. Inside the override, it can choose one with InterfaceName.super.method():

interface Hot { default String serve() { return "steaming"; } }
interface Iced { default String serve() { return "over ice"; } }

public class Tea implements Hot, Iced {
    @Override public String serve() { return Iced.super.serve() + ", or " + Hot.super.serve(); }
    public static void main(String[] args) {
        System.out.println(new Tea().serve());
    }
}
over ice, or steaming

A method inherited from a class always wins over an interface default.

Interface or abstract class?

Interface Abstract class
A class can have many one
Instance fields no (constants only) yes
Constructors no yes
Method bodies default, static, private any
Expresses “can do”: a capability “is a”: a shared base with state

Rules of thumb:

  • Start with an interface when you are describing a role that unrelated classes might play: Comparable, Runnable, Payable.
  • Use an abstract class when the subclasses share fields and code, and are genuinely kinds of the same thing.
  • They combine well: an interface for the type, plus an abstract class that implements the common parts (the Java collections do this with List and AbstractList).
  • Write code against the interface type: List<String> names = new ArrayList<>();. You can then swap the implementation without changing the callers. CITS4401 calls this “program to an interface”.

Exam-style checks

  • Give two differences between an interface and an abstract class, and one situation where each is the better choice.
  • Why must a method that implements an interface method be public?
  • What problem do default methods solve? What happens if two interfaces provide the same default?
  • Explain package-private access, and say what protected adds to it.
  • Where must the file for package au.lab.util; public class Maths be saved, and how do you run a class in that package?

Where to practise

Schildt’s Chapter 8 defines a queue interface with fixed, growable and circular implementations. Build it, then write one method that takes the interface type and works with all three. Separately, put two of your earlier classes into packages, compile them from the command line, and fix the access errors you get.