Arvutiteaduse instituut
  1. Kursused
  2. 2018/19 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (LTAT.NR.003)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2018/19 kevad

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

Inheritance

Object-oriented programming allows you to define new classes from existing classes. This is called inheritance. Inheritance is a powerful feature for reusing 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 inherited 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 a superclass.

Java supports inheritance incorporating the name of a superclass into the header of a 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, we can observe two classes, namely Person and Student. Using extends keyword, the Student inherits 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 public instance fields and method of Person superclass.

Note the following points regarding inheritance:

  • Private data fields and methods in a superclass are not accessible outside the class. Therefore, they cannot be used directly in a subclass. They can, however, be accessed/mutated through public accessors/mutators if 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 a Person class, even though they share common properties such as height and weight. A subclass and its superclass must 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 keyword extends in its header (e.g. class Person in the example) then our class automatically extends class Object. Check the methods of Object class in API.
  • The keyword super refers to the superclass and can be used to invoke the super-class’s methods and constructors.
    • 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 of the subclass’s constructor; this is the only way to explicitly invoke a superclass constructor.

Useful link:

Java documentation

Examples in diagrams

Object-oriented Programming in JavaTM Textbook

Session 5
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused