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.
Concept 1 of 5
Packages
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
Datein different packages. java.lang(String, Math, System) is imported automatically.- Compile and run from the
srcfolder using the full package path and name.
Concept 2 of 5
Access protection across packages
| Access from… | private | default | protected | public |
|---|---|---|---|---|
| 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 | ✗ | ✗ | ✗ | ✓ |
this (or its own type), but not through a reference to a plain superclass object.Interactive
Access-modifier checker
Concept 3 of 5
Interfaces
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 abstractby default; fields arepublic static finalconstants. - 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
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());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
| Interface | Abstract class | |
|---|---|---|
| Keyword | implements (many) | extends (only one) |
| Fields | Only public static final constants | Any fields, with any access |
| Constructors | None | Yes (called by subclasses) |
| Methods | abstract, default, static, private | abstract and concrete, any access |
| Relationship | “can do” — a capability (Comparable, Runnable) | “is a” — a common base with shared state |
| Use when | Unrelated classes share a role | Related 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));[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
interface Shape { double area(); } class Sq implements Shape { double area() { return 4; } }Show the solution
area() in Sq has default (package) access, which is weaker. Write public double area().Worked example 2 of 3
Worked example 2
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
interface I { int X = 10; } class A implements I { } System.out.println(A.X + I.X);Show the solution
Practice
Practice (1 of 2)
Try each one on paper first, then check your answer.
Show the answer
a. Can a subclass in package b use it?Show the answer
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.
Show the answer
Show the answer
default void hello()?Show the answer
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.