CodeGym /Java Blog /Inheritance in Java /Java Class Cast() Method
Author
Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

Java Class Cast() Method

Published in the Inheritance in Java group
In Java, there are different options for casting. One of them is the cast() method of the java.lang.Class class. it is used to cast the specified object to an object of this class. The method returns an object after being cast as an object.

Java Class Cast() Method Syntax

The Java Class Cast() method casts an object to the class or interface represented by this Class object. The documentation describes the cast() method as follows:

public T[] cast(Object obj),
where obj is the object to be cast. cast() method returns the object after casting, or null if obj is null. If the object is not null and is not assignable to the type T the method throws ClassCastException. Typically, class methods (such as cast() or isInstance() for example) are used in conjunction with generic types.

Java Class Cast() method code example

Here is a small demonstration of class.cast() method work:

class Parent {
   public static void print() {
       System.out.println("print Class Parent...");
   }
}

class Child extends Parent {
   public static void print() {
       System.out.println("print Class Child...");
   }
}

public class CDemo {

   public static void main(String[] args) {

       //Here we have Class cast() method
       //demonstration. Let’s have parent and child classes 
      // and make casting operation  

       Object myObject = new Parent();
       Child myChild = new Child();
       myChild.print();

       // casts object
       Object a = Parent.class.cast(myChild);

       System.out.println(myObject.getClass());
       System.out.println(myChild.getClass());
       System.out.println(a.getClass());
   }
}
The output here is the next:
print Class Child... class Parent class Child class Child
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION