Java course

Interfaces, inheritance, and exceptions

1.7.2 — Interfaces, inheritance, and exceptions

An interface declares methods that implementing classes provide. It lets the same calling code work with different kinds of object.

A class describes an object. new creates one, a dot calls its methods, and return gives a value back. String stores text.

Each code cell is a complete program with its own classes and inputs. Java starts in main; the statements inside its braces run in order. The other class declarations describe the objects used by main. Run each cell as a whole.

Declare a method in an interface

Greeting requires a method named message that returns a String. Its declaration ends with a semicolon because this interface does not supply the method body.

implements Greeting says HelloGreeting provides that method. The implementing method is public. @Override asks the compiler to check that it matches the interface method.

Choose behavior through the object

Both classes below implement Greeting. A Greeting variable can refer to either kind of object.

Calling message runs the implementation belonging to that object. The variable type describes which methods you can call; the object decides which implementation runs.

Inherit and replace a method

extends creates a subclass of another class. A subclass inherits accessible behavior and can override an instance method to provide different behavior.

The base Message returns Hello. LoudMessage overrides text to return HELLO! The variable is declared as Message, but its object is a LoudMessage, so the overridden method runs.

Use implements for an interface and extends for a superclass. A class can extend only one class.

A reference may hold no object

null means that a reference does not identify an object. Trying to call an instance method through null causes a NullPointerException.

This example catches that exception so the cell finishes. The problem is the call to greeting.message(), not the declaration of the Greeting interface.

Read a stack trace

A stack trace shows the exception type and where it happened. Lines beginning with at describe method calls. Read the first line for the problem, then the first line belonging to your program.

Here, main calls showGreeting, which calls message through null. Look for TraceExample.showGreeting and TraceExample.main in the output. Lines from NotebookKernel belong to the notebook runtime.

The exception is caught and deliberately printed with printStackTrace, so the notebook can continue.

Handle a rejected argument

An IllegalArgumentException reports an unsuitable argument. The constructor below rejects a negative count before storing it.

The catch block prints a useful message. After handling the exception, main continues to its final print statement.

Practice: provide an object

Replace Greeting greeting = null; with Greeting greeting = new HelloGreeting();. Leave the rest unchanged.

Run the cell. It should print Hello instead of Missing greeting.

Hint

Use new HelloGreeting() on the right of the assignment. The class below main already supplies message().

Worked solution
public class PracticeGreeting {
    public static void main(String[] args) {
        Greeting greeting = new HelloGreeting();
        if (greeting == null) {
            System.out.println("Missing greeting");
        } else {
            System.out.println(greeting.message());
        }
    }
}

interface Greeting {
    String message();
}

class HelloGreeting implements Greeting {
    @Override
    public String message() {
        return "Hello";
    }
}

Try the null case

In your completed cell, set greeting to null and run it. The null check should print Missing greeting without throwing an exception.

Value assigned to greetingExpected output
new HelloGreeting()Hello
nullMissing greeting

Enable JavaScript to run the Java notebook.