Chapter 5 |
Inheritance
Object-oriented programming allows us to define new classes from existing classes. This is called inheritance. Inheritance is a powerful feature, enabling reusing the software.
Using inheritance, we can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes. A class that is the base of inheritance is called a superclass (or a parent class or base class). The class that inherits features from a superclass is called a subclass (child class or extended class or derived class). A subclass inherits all public variables and methods defined by the superclass and adds its own, unique elements. Moreover, the subclass can also replace inherited behavior with new behavior as needed. Therefore, a subclass is a specialized version of the superclass.
Inheritance in Java is implemented by incorporating the name of superclass into the header of the subclass and the extends
keyword:
General syntax
class MySuperClass { ..... ..... } class MySubClass extends MySuperClass { // "extends" is the keyword used to inherit the superclass ..... ..... }
Example
Here is an example demonstrating Java inheritance. In this example, there are two classes: Person
and Student
. By using the extends
keyword, Student
inherits the method bodyMassIndex from the class Person
.
class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double bodyMassIndex(int mass, double height){ return (double)Math.round(mass*100/(height*height))/100; } } class Student extends Person { // subclass Student extends superclass Person private String university; public Student(String name, String university) { super(name); // invoke the constructor of the superclass this.university = university; } public String getUniversity() { return university; } public void setUniversity(String university) { this.university = university; } public double avgGrade(int[] grades) { int sum = 0; for (int g : grades) sum += g; return sum*1.0/grades.length; } } public class Test { public static void main(String[] args) { Student maria = new Student("Maria", "University of Tartu"); // Student object has an access to Person class methods double BMI = maria.bodyMassIndex(50, 1.75); double averageGrade = maria.avgGrade(new int[]{5,5,5,5}); System.out.println(maria.getName() + "'s BMI is " + BMI + " and average grade is " + averageGrade); } }
The program output is:
Maria's BMI is 16.33 and average grade is 5.0
In the given program, when an object of Student
subclass is created, it can access public instance fields and method of the Person
superclass.
Note the following points regarding inheritance:
- Private data fields and methods of a superclass are not accessible outside the class. Therefore, they cannot be used directly in the subclass. They can, however, be accessed/mutated through public accessors/mutators, if those are defined in the superclass.
- Inheritance is used to model a relationship. Do not blindly extend a class just for the sake of reusing methods. For example, it makes no sense for a
Tree
class to extend aPerson
class, even though they share common properties such as height and weight. A subclass and its superclass should have the is-a relationship. - A Java class may inherit directly from only one superclass. This restriction is known as single inheritance. If you use the
extends
keyword to define a subclass, it allows only one parent class. (Nevertheless, multiple inheritance can be achieved through interfaces, which will be introduced next week.) - In general, all classes have a parent class (except one). The class at the top of the Java class hierarchy is called
Object
; it does not have a parent class. When we create our own class and do not use the keywordextends
in its header (e.g. classPerson
in the example above), then our class automatically extends the classObject
. Check the methods ofObject
class in Java API. - The keyword
super
refers to the superclass and can be used to invoke the methods and constructors of the super-class.- The statement super() invokes the no-arg constructor of its superclass; and the statement super(arguments) invokes the superclass constructor that matches the arguments. The statement super() or super(arguments) must be the first statement in the constructor; this is the only way to explicitly invoke the constructor of the superclass.
Useful links
Java documentation about inheritance.
Examples with diagrams of superclasses and subclasses.
Chapter of Object-oriented Programming in Java Textbook.
Chapter 5 |