Calling Methods in Parent Class

Sometimes we may want to call the parent version of a method from the child class. As an example, suppose agian 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;
    }
}

Suppose we wanted our Student print method to FIRST print “I am a person” and THEN print “I am a student”. We could do this with two print statements, or we could call the print method for Person from inside the Student print method. Here’s the format for calling a parent method from inside the child class:

super.methodName(args)

So, here is our revised print method for Student:

public void print() 
{
    //Will go to Person's print method, and print "I am a person."
    super.print();

    System.out.println("I am a student.");
}