Institute of Computer Science
  1. Courses
  2. 2017/18 spring
  3. Object-Oriented Programming (Narva College) (P2NC.01.083)
ET
Log in

Object-Oriented Programming (Narva College) 2017/18 spring

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
Session 5

Inheritance

Inheritance is one of the foundation principles of object-oriented programming because it allows the creation of hierarchical classifications. In Java (and many other programming languages), the classes form a class hierarchy or inheritance tree.

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, each adding those things that are unique to it. A class that is inherited is called a superclass (or derived class, child class). The class that does the inheriting is called a subclass (or derived class, child class). Therefore, a subclass is a specialized version of a superclass. It inherits all of the 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.

The inheritance of classes can repeatedly continue until the hierarchy tree becomes as deep as needed. On the other hand, the child class receives the features inherited from its superclass, which also has received the features inherited from its own superclass and so on to the java.lang.Object class.

Note that we can specify only one superclass for any subclass - it is not possible to extend more than one class. This is called single inheritance. Java does not support the inheritance of multiple superclasses into a single subclass. However, we can create a hierarchy of classes in which a subclass becomes a superclass of another subclass. Of course, no class can be a superclass of itself.

NB! If there is a need to inherit from multiple classes, the best option is through interfaces, described in the next practical.

A major advantage of inheritance is that once you have created a superclass that defines the attributes common to a set of objects, it can be used to create any number of more specific subclasses.

Java supports inheritance by allowing one class to incorporate another class into its declaration. This is done by using the extends keyword. Thus, the subclass adds to (extends) the superclass.

General syntax

class Super {
   .....
   .....
}
class Sub extends Super { // extends is the keyword used to inherit the superclass
   .....
   .....
}

By adding the extends keyword to the header of the subclass, we are telling Java that this subclass inherits all the superclass's public fields and methods.

Note: subclasses do not inherit private instance fields or private methods from their superclasses.

Example

Here is an example demonstrating Java inheritance. In this example, we can observe two classes, namely Person and Student. Using extends keyword, the Student inherits the method bodyMassIndex() of Person class.

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 lisa = new Student("Lisa","University of Tartu");
        // Student object has an access to Person class methods
        double BMI = lisa.bodyMassIndex(50,1.75);  
        double averageGrade = lisa.avgGrade(new int[]{5,5,5,5});
        System.out.println(lisa.getName() + "'s BMI is " + BMI + " and average grade is " + averageGrade);
    }
}

The program output is:

 Lisa'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 the instance fields and method of Person superclass.

Note that:

  • inheriting a class does not overrule the private access restriction. Thus, even though a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared private. In such cases use accessors.
  • the super keyword is similar to this keyword. The super keyword is used:
    • to differentiate the fields and methods of the superclass from the fields and methods of a subclass, if they have same names;
    • to invoke the superclass constructor from subclass.
  • constructors are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass:
    • the keyword super() must be the first statement in the subclass's constructor. If there are several constructors in the superclass, the one that matches the argument list in super() will be used.

Useful link:

Java documentation

Examples in diagrams

Object-oriented Programming in JavaTM Textbook

Session 5
  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment