Creating Variables

Suppose 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;
    }
}

We can create Person objects just as we’ve done before. For example:

Person p = new Person("Bob", 26);

We can also create new Student objects as we’ve done before:

Student s = new Student("Lisa", 18, "PSYCH", 3.25);

We can also call the print method for both of these variables. (Student inherits print() because it extends Person.)

p.print();
s.print();

Both of these method calls print “I am a person.”

Since every Student is also a Person (because Student extends Person), a Student can also be stored in a Person variable:

Person ps = new Student("Fred", 20, "ECE", 3.1);

However, not all people are students, so we can’t store a Person in a Student variable:

//NO! This will not compile - not all people are students.
Student bad = new Person("Jane", 30);