A class
can be based upon another (derived from it). This requires the "extends" keyword in the class
declaration. One class
extends another.
Java does not allow a class
to extend multiple other classes. This reduces problems with inheriting state, like fields, from many parents.
Let us begin with a simple "extends" example. Here class
B extends class
A. Usually longer, more descriptive class
names are best.
call()
method is implemented on both A and B. The most derived B implementation is used when an A reference is acted upon.class A { public void call() { System.out.println("A.call"); } } class B extends A { public void call() { System.out.println("B.call"); } } public class Program { public static void main(String[] args) { // Reference new B class by A type. A a = new B(); // Invoke B.call from A class instance. a.call(); } }B.call
Here we have an Animal class
with one method. We then have a Dog class
that derives from Animal. In main()
we can use one method on Animal.
class
we can use the methods from Animal and Dog. So the dog can breathe()
and bark()
.class
depends on what your program is doing.class Animal { public void breathe() { System.out.println("Breathe"); } } class Dog extends Animal { public void bark() { System.out.println("Woof"); } } public class Program { public static void main(String[] args) { // On an animal we can call one method. Animal animal = new Animal(); animal.breathe(); // On a dog we can use Animal or Dog methods. Dog dog = new Dog(); dog.breathe(); dog.bark(); } }Breathe Breathe Woof
We cannot use "extends" on multiple classes. A class
can only inherit from one class
. This avoids problems where fields (state) is inherited from many classes at once.
In extending classes, we gain the parent's fields and methods. And we add in all that parent's extended classes. We compose complex and powerful programs.