Chapter 5 |
Overriding
In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method from its superclass, then we have a chance to override it. In the class hierarchy, when a method in a subclass has the same return type and signature (name and parameter list) as the 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 in the subclass instance. The parent's method can be invoked using super
keyword.
Example
This example demonstrates method overriding. In this program, we have two classes, namely Person
and Student
; both of them contain bodyMassIndex method. If the object of the 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 Iceland"); // instance of Student class System.out.println(moona.bodyMassIndex(60, 1.80)); // method of Person class System.out.println(lisa.bodyMassIndex(50, 1.7)); // overridden 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
Chapter 5 |