Home » Java programming language

Java Class class cast() method with example

Class class cast() method: Here, we are going to learn about the cast() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 22, 2019

Class class cast() method

  • cast() method is available in java.lang package.
  • cast() method casts this Object to the class or an interface denoted by this Class object.
  • cast() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • cast() method may throw ClassCastException at the time of casting an Object.
    ClassCastException: In this exception when the given object is not null.

Syntax:

    public Type cast(Object o);

Parameter(s):

  • Object o – represents the object to be cast.

Return value:

The return type of this method is Type, it returns the following values based on the given cases,

  • It returns the casting object.
  • It returns null when the given Object is null.

Example:

// Java program to demonstrate the example 
// of Type cast(Object o) method of Class 

class A1 {
 // A1 Blank implementation
}

class B1 extends A1 {
 // B1 Blank implementation
}

public class MainClass {
 public static void main(String[] args) {
  // Creting an instance of MainClass
  MainClass mc = new MainClass();

  // Display Class
  System.out.println("mc.getClass():" + mc.getClass());

  // Creating an instance of class A1 and B1
  A1 a = new A1();
  B1 b = new B1();

  // Casting object b to a by using cast(b) method
  Object a1 = A1.class.cast(b);

  // Display Class of object a , b and a1
  System.out.println("a.getClass(): " + a.getClass());
  System.out.println("b.getClass(): " + b.getClass());
  System.out.println("a1.getClass(): " + a1.getClass());
 }
}

Output

mc.getClass():class MainClass
a.getClass(): class A1
b.getClass(): class B1
a1.getClass(): class B1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.