Java Reference
In-Depth Information
return "Person: " + super.id + " has EmployeeID " + this.id;
}
Of course, now that you know about information hiding, it would be better still to access the ID of
the superclass using a getter.
method overriding
It was mentioned already that subclasses inherit methods from their superclass. This means that if
the
Student
class has a
calculateGPA()
method, then
Graduate
and
Undergraduate
will have
this method either implicitly or explicitly as well. The subclasses can, however, override the method
with a new, specialized implementation. This is called method overriding. Note, this is not related to
method overloading discussed earlier in this chapter.
Consider the
calculateGPA()
method from the
Student
class. The
Student
class has a
double[]
variable called
grades
that lists all the students' grades. The
calculateGPA()
method then just cal-
culates the average of these grades.
public double calculateGPA() {
double sum = 0;
int count = 0;
for (double grade : this.grades){
sum += grade;
count++;
}
return sum/count;
}
Now, suppose graduate students only get credit for grades above a certain minimum, for example
only 80 percent and higher are accepted, and courses with a grade below 80 must be repeated. Then
for the
Graduate
class, you might want to calculate the GPA based only on those higher grades. To
do this, you can override the
calculateGPA()
method using the
@Override
annotation and change
the implementation in the subclass.
@Override
public double calculateGPA(){
double sum = 0;
int count = 0;
for (double grade : this.getGrades()){
if (grade > minGrade){
sum += grade;
count++;
}
}
return sum/count;
}
polymorphism
Polymorphism is a key concept in Object‐Oriented Programming and is closely related to inheri-
tance. Because inheritance models an “is a” relationship, one instance can take on the behaviors and
attributes of more than one class. According to the class hierarchy of the
Person
example, a
Master
Search WWH ::
Custom Search