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, class B that extends A and has an int field and class C that extends B and also has an int field.
  • Class B has a constructor using its int field and overrides the toString() 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 the toString() API method of Object.
  • We create three new objects from the three classes and print them.
  • Then we cast the C object to an A object and the C object to a new C 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;


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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button