Prerequisite : Inheritance
In Java, all non-static methods are based on the runtime type of the underlying object rather than the type of the reference that points to that object. Therefore, it doesn’t matter which type you use in the declaration of the object, the behavior will be the same.
How to Refer a subclass object
There are two approaches to refer a subclass object. Both have some advantages/disadvantages over the other. The declaration affect is seen on methods that are visible at compile-time.
Consider an example explaining both the approaches.
seat height of first bicycle is 25 No of gears are 3 speed of bicycle is 100 seat height is 25 No of gears are 4 speed of bicycle is 200 seat height is 20
Explanation of above program :
MountainBike mb1 = new MountainBike(3, 100, 25);
Now we again create object of MountainBike class but this time it is referred by using superclass Bicycle reference ‘mb2’. Using this reference we will have access only to those parts(methods and variables) of the object defined by the superclass.
Bicycle mb2 = new MountainBike(4, 200, 20);
Since the reference ‘mb1’ have access to field ‘seatHeight’, so we print this on console.
System.out.println("seat height of first bicycle is " + mb1.seatHeight);
System.out.println(mb1.toString()); System.out.println(mb2.toString());
System.out.println("seat height of second bicycle is " + mb2.seatHeight);
mb2.setHeight(21);
Use of type casting In above example, we have seen that by using reference ‘mb2’ of type Bicycle, we are unable to call subclass specific methods or access subclass fields. This problem can be solved using type casting in java. For example, we can declare another reference say ‘mb3’ of type MountainBike and assign it to ‘mb2’ using typecasting.
// declaring MountainBike reference MountainBike mb3; // assigning mb3 to mb2 using typecasting. mb3 = (MountainBike)mb2;So, now the following statements are valid.
System.out.println("seat height of second bicycle is " + mb3.seatHeight); mb3.setHeight(21);
When to go for first approach (Referencing using superclass reference)