Method Overriding
Suppose again that we have the Person and Student classes from earlier in the chapter:
public class Person
{
protected String name;
protected int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public void print()
{
System.out.println("I am a person.");
}
}
public class Student extends Person
{
private String major;
private double gpa;
public Student(String n, int a, String m, double g)
{
super(n, a);
this.major = m;
this.gpa = g;
}
}Currently, when we call print with a
Student variable, “I am a person” is printed. However, maybe we want to print “I am a
person” for objects of type Person, and print “I am a student” for objects of type
Student. I can accomplish this by overriding the print method to indicate that we don’t want to
use the inherited method, but would instead like to create our own version of that method.
To do this, I just create another print method in the Student class:
public void print()
{
System.out.println("I am a student.");
}When overriding a method, the version in the child class must have exactly the same header as the version in the parent class. This means the same return type, name, and arguments.
Now, when we call print with a Student object, it will print “I am a student.” For example:
Student s = new Student("Lisa", 18, "PSYCH", 3.25);
Person ps = new Student("Fred", 20, "ECE”", 3.1);
s.print(); //prints "I am a student."
ps.print(); //prints "I am a student."