Object Casting Java
Object Casting Java
What is casting?
Assigning one data type to another or one object to another is known as casting. Java supports two types
of casting data type casting and object casting.
Conditions of assigning objects of different classes one to another
Same class objects can be assigned one to another and it is what we have done with Officer1 class.
Subclass object can be assigned to a super class object and this casting is done implicitly. This is
known as upcasting (upwards in the hierarchy from subclass to super class).
Java does not permit to assign a super class object to a subclass object (implicitly) and still to do
so, we need explicit casting. This is known as downcasting (super class to subclass). Downcasting
requires explicit conversion.
Program explaining the above rules of Java Object Casting
class Flower
{
public void smell()
// parent class method
{
System.out.println("All flowers give smell, if you can smell");
}
}
public class Rose extends Flower
{
public void smell()
// child class method
{
System.out.println("Rose gives rosy smell");
}
public static void main(String args[])
{
Flower f = new Flower();
Rose r = new Rose();
f.smell();
// Parent class object accessing parent class method
r.smell();
// Child class object accessing child class method
f = r;
f.smell();
// r = f;
r = (Rose) f;
f.smell();
}
}
Output
D:\lab>javac Rose.java
D:\lab>java Rose
All flowers give smell, if you can smell
Rose gives rosy smell
Rose gives rosy smell
Rose gives rosy smell
The super class Flower includes only one method smell() and it is overridden by subclass Rose.
f.smell();
// I
r.smell();
// II
In the above two statements, nothing is new as both object are calling their own smell() methods.
Object Casting Java 1