class
Class casting example
With this example we are going to demonstrate how to cast an object of a class to another class. In short, to cast an object of a class to another class we have followed the steps below:
- We have created class
A
, classB
that extendsA
and has an int field and classC
that extendsB
and also has an int field. - Class
B
has a constructor using its int field and overrides thetoString()
API method of Object. - Class
C
also has a constructor using two int fields, where it initializes the super field using the super constructor with the first given int value, and then initializes its own int field with the second given int value. It also overrides thetoString()
API method of Object. - We create three new objects from the three classes and print them.
- Then we cast the
C
object to anA
object and theC
object to a newC
object and print them.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class ClassCast { public static void main(String[] argv) { A aObject = new A(); B bObject = new B(1); C cObject = new C(2, 3); System.out.println("A = " + aObject); System.out.println("B = " + bObject); System.out.println("C = " + cObject); A aCasted = cObject; System.out.println("aCasted = " + aCasted); C secondC = (C) aCasted; System.out.println("secondC = " + secondC); } } class A { } class B extends A { int a; B(int i) { a = i; } public String toString() { return "In a B object: " + a; } } class C extends B { int b; C(int i, int j) { super(i); // does "one = i" for us. b = j; } public String toString() { return "In a C object: " + a + "," + b; } }
Output:
A = methodoverloading.A@e9f784d
B = In a B object: 1
C = In a C object: 2,3
aCasted = In a C object: 2,3
secondC = In a C object: 2,3
This was an example of how to cast an object of a class to another class in Java.