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

Overriding

In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method from its superclass, then there is a chance to override it. In a class hierarchy, when a method in a subclass has the same return type and signature (the name and the parameter list of a method) as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden from the subclass instance. The parent's method can be invoked using super keyword.

Example

This example demonstrates method overriding. In this program, we can observe two classes, namely Person and Student; both of them contain bodyMassIndex method. However, if the object of class Person calls the method, only index is calculated; if the object of class Student calls the method, a sentence is printed out and the index is calculated. (Important: if the super keyword is omitted, the program falls into an infinite recursion!)

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) {
        System.out.print(name + ", your BMI is: ");
        return (double)Math.round(mass*100/(height*height))/100;
    }
}


class Student extends Person {

    private String university;

    public Student(String name, String university) {
        super(name);
        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/grades.length;
    }

    // overriden method which prints a sentence and calculates BMI
    public double bodyMassIndex(int mass, double height) {
        System.out.println("We are in the subclass");
        return super.bodyMassIndex(mass, height);     // use the method from the superclass
    }
}


public class Test {
    public static void main(String[] args) {
        Person moona = new Person("Moona");     // instance of Person class
        Student lisa = new Student("Lisa","University of Tartu"); // instance of Student class
        System.out.println(moona.bodyMassIndex(60,1.80));   // method of Person class
        System.out.println(lisa.bodyMassIndex(50,1.7));     // overrided method of Student class

        // moona.avgGrade(new int[]{5,5,5,5});      // this method is not visible to superclass
        double averageGrade = lisa.avgGrade(new int[]{5,5,5,5});
        System.out.println(lisa.getName() + "'s average grade is " + averageGrade);
    }
}

The program output is:

 Moona, your BMI is: 18.52
 We are in the subclass
 Lisa, your BMI is: 17.3
 Lisa's average grade is 5.0
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