Reference · module 6
Inheritance and exceptions
Everything this module explains, on one page.
extends
Build a class on top of another with extends.
- class Cat extends Animal makes Cat a kind of Animal: it gets all of Animal's fields and methods and can add its own. Java allows only one parent class.
- super(...) in the child's constructor calls the parent's constructor, and it must be the first line: Cat(String name) { super(name); }
- A child can replace a parent's method with its own version. @Override above it asks the compiler to check that a method with that signature really exists in the parent.
The mistake you are about to make
class Cat extends Animal, Pet
class Cat extends Animal implements Pet
Some languages allow several parents, so a list looks natural. Java allows one extends; extra abilities come through interfaces.
Interfaces
Promise abilities with interfaces and implement them.
- An interface lists methods a class promises to have, without saying how: interface Shape { double area(); } It describes an ability, not an object.
- class Circle implements Shape must then write area() itself. A class can implement several interfaces at once: implements Shape, Comparable<Circle>.
- A variable of the interface type can hold any class that implements it: Shape s = new Circle(2); Code written for Shape then works for circles, squares and anything added later.
The mistake you are about to make
Shape s = new Shape();
Shape s = new Circle(2);
Shape is a type like any class, so new Shape() looks fine. An interface has no implementation and cannot be created; create a class that implements it.
Exceptions
Catch errors with try and catch instead of crashing.
- When something goes wrong at runtime, Java throws an exception and the program stops. Integer.parseInt("abc") throws NumberFormatException.
- try { ... } catch (NumberFormatException e) { ... } runs the try block, and if that exception happens, jumps to catch instead of crashing. The code after catch continues normally.
- A finally block runs whether an exception happened or not, which suits closing files. Catch the specific exception you expect rather than every Exception.
The mistake you are about to make
catch (Exception e) { }
catch (NumberFormatException e) { System.out.println("Not a number"); }
Catching everything and doing nothing makes the error disappear. It also hides real bugs; catch what you expect and handle it.