Casting Objects

2 0 0
                                    

Type casting of an object depends merely on the hierarchy of the object. Let us use the Mother of all class which is Object.

=====================

class TypeCastingDemo {
void displayHelloWorld(){
System.out.println("Hello World!");
}
public static void main(String[] args) {
Object obj = new TypeCastingDemo();
if(obj instanceof TypeCastingDemo) {
TypeCastingDemo demo = (TypeCastingDemo)obj;
demo.displayHelloWorld();
}
}
}

=====================

Result:

Hello World!


Object obj = new TypeCastingDemo();

    - This code means we created an object of the class TypeCastingDemo and we assigned it to a variable named obj with a type Object class. This was allowed since Object is the superclass of TypeCastingDemo class. If you do the opposite, it will lead into an error:

    TypeCastingDemo obj = new Object(); // The error would be, the required type is TypeCastingDemo but you provided an Object.

obj instanceof TypeCastingDemo

    - This reads to "is obj an instance(an object) of TypeCastingDemo". And the answer is true.

(TypeCastingDemo)obj

    - we convert obj of type Object to type TypeCastingDemo by using explicit type casting. We put the type of the new object inside the parenthesis before the name of the old object we want to convert.

So, basically type casting of an object is just the conversion of that object type to another object type as long as it adheres to the hierarchy of the classes.

Java ProgrammingWhere stories live. Discover now