Creating Objects with Subclasses and Superclasses
When you create an object in Java, the type of the variable does not have to match the type of the object exactly. If a class extends a superclass, you can store an object of the subclass in a variable whose type is the superclass.
This works because every subclass is a type of its superclass.
Suppose you have the following class hierarchy:
PersonStudentTeacher
A Student is-a Person, and a Teacher is-a Person.
Creating an Object of a Subclass
You can create an object of a subclass just as you would any other object.
In this example:
- The reference type is
Student. - The object type is
Student.
Because the reference type and object type are the same, you can use all of the methods defined in Student and those inherited from Person.
Creating an Object of a Subclass with Superclass Reference
You can also store a subclass object in a variable whose type is the superclass.
In this example:
- The reference type is
Person. - The object type is
Student.
Although the object is a Student, the variable is declared as a Person.
This means you can call methods that are defined in Person.
However, you cannot call methods that exist only in Student.
At compile time, the examines the type of the reference. The compiler only knows that person is a Person, so it only allows access to members of the Person class.
In order to call methods of Student, you will need to typecase person to a Student to signal the compiler to look at the Student class methods.
Why Use a Superclass Reference?
Using the superclass as the reference type makes your code more flexible.
For example, a method that works with Person objects can accept both Student and Teacher objects. Consider both Student and Teacher class have their own void introduce() method. A method can be written to introduce any object of type Person.
You can call the method with either subclass.
Because both Student and Teacher are Person objects, the same method can work with either one.
This is especially helpful if you have a list of data that is a mix of Student and Teacher. The list can be of type Person.