TurkuBasicOOPinJava / Week 6: Methods of OO Programming /11A. TYPE Conversions OR CASTING+++
KaiquanMah's picture
int approximation = (int) height;
f0c87c9 verified
As the type of a variable affects which features of an object can be referenced through it,
it's necessary to be able to change the type of the reference.
This is done through EXPLICIT TYPE CASTING.
We have previously used type casting, for example, when converting floating point numbers to integers:
double height = 175.25;
int approximation = (int) height;
As previously noted, when class "Student" inherits from class "Person", a "Person"-type variable can be assigned a reference to a "Student" object.
However, this restricts the operations that can be used to those defined in the "Person" class.
Since the object is of type "Student", we can perform a type casting if necessary.
After the type casting, the properties defined in the "Student" class are available:
Person person = new Student("Oliver Student", "oliver@example.com", 14);
// Through the variable 'person', we cannot now request study credits,
// as the class has not defined the method.
// So let's do
// 'type casting'
// FROM 'Person' class to 'Student' class
Student oliver = (Student) person;
// approach 1 - BEST (less confusing)
System.out.println("Oliver's study credits: " + oliver.getStudyCredits());
// approach 2
// this also works, but it's starting to be quite a confusing line
System.out.println("Oliver's study credits: " + ((Student) person).getStudyCredits());
If we have an object created from the "Student" class and a "Student"-type variable,
and we want to refer to the object with a "Person"-type variable, no type casting is needed.
This is because all students are people, but only some people are students:
Student oliver = new Student("Oliver", "12354", 123);
// This is OK WITHOUT TYPE CASTING, because all
// Students are Persons
Person oliverAsPerson = oliver;
// This is also the same reason
Object oliverAsObject = oliver;
// VS
// The other way around requires conversion
Student oliver2 = (Student) oliverAsPerson;
Person oliverAsPerson2 = (Person) oliverAsObject;