Java Class.cast(Object obj)
Syntax
Class.cast(Object obj) has the following syntax.
public T cast(Object obj)
Example
In the following code shows how to use Class.cast(Object obj) method.
class A {/* www .j a v a 2s. c o m*/
public static void show() {
System.out.println("Class A show() function");
}
}
class B extends A {
public static void show() {
System.out.println("Class B show() function");
}
}
public class Main {
public static void main(String[] args) {
Main cls = new Main();
Class c = cls.getClass();
System.out.println(c);
Object obj = new A();
B b1 = new B();
b1.show();
// casts object
Object a = A.class.cast(b1);
System.out.println(obj.getClass());
System.out.println(b1.getClass());
System.out.println(a.getClass());
}
}
The code above generates the following result.