Home
9Packages & Interfaces
9

Topic 9 of 13 · Lectures 13–14

Packages & Interfaces

Organising classes into packages, how access modifiers work across packages, defining and implementing interfaces, default and static interface methods, and choosing between interfaces and abstract classes.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

An Employee and an Invoice have nothing in common — except that the accounts office must pay both. How can one loop pay them all?

Neither class should extend the other. Instead both can promise, through an interface, that they have a getPayment() method. The loop only needs that promise.

First, though, we organise classes into packages — and see how packages change what protected and default access mean.

Outline · Lectures 13–14

Topics in this chapter

Select a topic to jump to the slide that explains it.

  1. Packages and import
  2. Access protection
  3. Defining and implementing interfaces
  4. Multiple interfaces
  5. Interfaces vs. classes

Concept 1 of 5

Packages

Package names mirror the folder structure. Reverse domain names keep them unique.

Packages

// file: src/bd/edu/green/cse/model/Student.java
package bd.edu.green.cse.model;   // first line

public class Student { ... }

// file: src/bd/edu/green/cse/app/Main.java
package bd.edu.green.cse.app;
import bd.edu.green.cse.model.Student;   // one class
import java.util.*;                      // whole package

public class Main { ... }
  • A package groups related classes and gives them a namespace: two classes may both be called Date in different packages.
  • java.lang (String, Math, System) is imported automatically.
  • Compile and run from the src folder using the full package path and name.

Concept 2 of 5

Access protection across packages

Access from…privatedefaultprotectedpublic
the same class✓✓✓✓
another class in the same package✗✓✓✓
a subclass in the same package✗✓✓✓
a subclass in another package✗✗✓✓
an unrelated class in another package✗✗✗✓
Subtle point: A subclass in another package can use an inherited protected member through this (or its own type), but not through a reference to a plain superclass object.

Interactive

Access-modifier checker

Concept 3 of 5

Interfaces

UML: a dashed line with a hollow triangle means “implements”.

Interfaces

interface Payable {
    double getPayment();          // public abstract
}
class Invoice implements Payable {
    private int qty; private double price;
    Invoice(int q, double p) { qty = q; price = p; }
    @Override
    public double getPayment() { return qty * price; }
}
  • An interface declares what a class can do; implementing classes decide how.
  • Interface methods are public abstract by default; fields are public static final constants.
  • You cannot create an object of an interface, but you can use it as a type: Payable p = new Invoice(3, 250);

Step through the code

Trace: paying through an interface

The array’s type is Payable[], yet each call runs the method of the real object.

Step through the code

Trace: paying through an interface (cont.)

Interactive

Interface contract checker

Concept 4 of 5

Multiple interfaces

A class extends one class but may implement any number of interfaces.

Concept 4 of 5

Multiple interfaces (cont.)

interface Flyable   { void fly(); }
interface Swimmable { void swim(); }
class Bird { void layEggs() { } }

class Duck extends Bird implements Flyable, Swimmable {
    public void fly()  { System.out.println("Duck flies"); }
    public void swim() { System.out.println("Duck swims"); }
}
Flyable f = new Duck();   f.fly();
Swimmable s = new Duck(); s.swim();
  • No diamond problem: interfaces (traditionally) carry no state and no competing method bodies.
  • Interfaces can extend other interfaces: interface Amphibious extends Flyable, Swimmable {}.

Code example

default, static and private interface methods

interface Greeter { String name(); // abstract default String greet() { // Java 8 return "Hello, " + decorate(name()); } static Greeter of(String n) { // Java 8 return () -> n; // lambda implements name() } private String decorate(String s) { // Java 9 return "*" + s + "*"; } } class Teacher implements Greeter { public String name() { return "Sir"; } public String greet() { return "Good morning, " + name(); } // override default } System.out.println(Greeter.of("Ayan").greet()); System.out.println(new Teacher().greet());
Output
Hello, *Ayan*
Good morning, Sir
  • default methods add behaviour to an interface without breaking existing implementing classes.
  • static methods are helpers called on the interface name.
  • private methods share code between default methods.

Step through the code

Trace: default, static and private methods

Which method body actually runs? The lambda object gets the default greet(); Teacher overrides it.

Step through the code

Trace: default, static and private methods (cont.)

Concept 5 of 5

Interface vs abstract class

InterfaceAbstract class
Keywordimplements (many)extends (only one)
FieldsOnly public static final constantsAny fields, with any access
ConstructorsNoneYes (called by subclasses)
Methodsabstract, default, static, privateabstract and concrete, any access
Relationship“can do” — a capability (Comparable, Runnable)“is a” — a common base with shared state
Use whenUnrelated classes share a roleRelated classes share code and fields

Code example

A library interface: Comparable

import java.util.Arrays; class Student implements Comparable<Student> { String name; double cgpa; Student(String n, double c) { name = n; cgpa = c; } @Override public int compareTo(Student o) { // negative, 0 or positive return Double.compare(o.cgpa, cgpa); // higher CGPA first } public String toString() { return name + "" + cgpa; } } Student[] list = { new Student("Rahim", 3.15), new Student("Sadia", 3.91), new Student("Nabila", 3.47) }; Arrays.sort(list); // uses compareTo System.out.println(Arrays.toString(list));
Output
[Sadia 3.91, Nabila 3.47, Rahim 3.15]

Because Student implements Comparable, the library’s Arrays.sort can order students without knowing anything else about them.

Worked example 1 of 3

Worked example 1

Why does this not compile? interface Shape { double area(); } class Sq implements Shape { double area() { return 4; } }
Show the solution
Interface methods are public; area() in Sq has default (package) access, which is weaker. Write public double area().

Worked example 2 of 3

Worked example 2

A class Robot must be both Movable and Chargeable, and it already extends Machine. Write the header.
Show the solution
class Robot extends Machine implements Movable, Chargeable { ... }
extends comes first; any number of interfaces follow implements.

Worked example 3 of 3

Worked example 3

What does this print? interface I { int X = 10; } class A implements I { } System.out.println(A.X + I.X);
Show the solution
20. X is a public static final constant inherited by A.

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. What is the purpose of the package statement and where must it appear?
Show the answer
It puts the class in a named package (a namespace and folder); it must be the first statement in the file (only comments may come before it).
2. A field is declared with no modifier in package a. Can a subclass in package b use it?
Show the answer
No — default access is package-only. It would need to be protected or public.
3. Write an interface Resizable with void resize(double factor) and implement it in Circle.
Show the answer
interface Resizable { void resize(double factor); }
class Circle implements Resizable {
    private double r;
    public void resize(double f) { r *= f; }
}

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. Can an interface have a constructor? A field that changes?
Show the answer
No constructor. Fields are implicitly public static final constants, so they cannot change.
5. Give one reason to prefer an interface over an abstract class.
Show the answer
A class can implement many interfaces but extend only one class; interfaces let unrelated classes share a role.
6. What happens if a class implements two interfaces that both have default void hello()?
Show the answer
Compile error unless the class overrides hello(); inside it can pick one with A.super.hello().

Check yourself

Quiz

Summary

Summary

  • Packages group classes into namespaces that mirror folders; import brings in names from other packages.
  • Across packages only public (and protected, for subclasses) members are reachable.
  • An interface is a contract of public methods; classes implement it and can implement many.
  • Interfaces may have default, static and private methods, and constants — but no instance fields or constructors.
  • Interface = can-do role for unrelated classes; abstract class = is-a base that shares code and state.