Casting of Reference Types in Java

Casting is the conversion of data of one type to another type either implicitly or explicitly.  

Casting happens for both primitive types and reference types. 

If the casting operation is safe, java will do automatic type casting. This is called implicit type casting. 

If java can't be sure whether the casting will be safe, java will not do automatic casting, but programmer can do the casting if he is sure about the outcome. This is called explicit type casting.

Both types should be compatible in both implicit and explicit casting. We cannot cast two unrelated classes  implicitly or explicitly. 

 

Automatic type casting for reference types

In case of reference types, a child object or child reference variable can be assigned to a parent reference variable. 

Parent can be a class, abstract class or interface. 

Class A{}

Class B extends A{}

A a = new B();

 

Explicit type casting for reference types

The types should be compatible for both implicit and explicit casting.

In case of reference types, when we assign a child type object to a parent type, no explicit cast is required.

When assigning a parent type variable to child type variable, an explicit cast is required. However you need to make sure that the parent type reference variable is referring to a child object; else you will get a ClassCastException at runtime.

Class A{}

Class B extends A{}

A a = new B();

B b = (B)a; //Variable a actually hold a B object. So no ClassCastException will happen at runtime.

A aa = new A();

B bb = (B)aa; //Variable aa actually hold an A object. So ClassCastException will happen at runtime.

 

Example

Find, which all lines within the main method will compile and which all lines will run successfully and print childMethod!

package com.javajee;

public class Parent {

  public static void main(String[] args) {

    Parent parentRefP = new Parent();

    Parent parentRefC = new Child();

    Child childRef = new Child();

    parentRefC.childMethod(); //line 1

    (Child)parentRefC.childMethod(); //line 2

    ((Parent)parentRefC).childMethod(); //line 3

    ((Child) parentRefC).childMethod(); // line 4

    ((Child) parentRefP).childMethod(); // line 5

    childRef.childMethod(); // line 6

    (Parent)childRef.childMethod(); //line 7

    ((Parent)childRef).childMethod(); //line 8

  }

}



class Child extends Parent {

  public void childMethod() {

    System.out.println("childMethod!");

  }

}

 

Answer

Following lines will compile and print childMethod!:

  • ((Child) parentRefC).childMethod(); // line 4

  • childRef.childMethod(); // line 6

Following line will compile, but will throw ClassCastException at runtime:

  • ((Child) parentRefP).childMethod(); // line 5 - Reason: By casting as Child, we are telling java to treat the reference as Child, and will provide a Child object at runtime. However parentRefP refers to a Parent object. 

Following lines will not compile:

  • parentRefC.childMethod(); //line 1 - Reason: You cannot call a child method using a parent reference. 

  • (Child)parentRefC.childMethod(); //line 2 - Reason: Wrong way to caste; you need to caste an object and then call a method on the casted object, which requires paranthesis around the reference and casting as in line 4.

  • ((Parent)parentRefC).childMethod(); //line 3 - Reason: By casting as Parent, we are telling java to treat the reference as Parent, and you cannot call a child method using a parent reference. 

  • (Parent)childRef.childMethod(); //line 7 - Reason: Wrong way to caste; you need to caste an object and then call a method on the casted object, which requires paranthesis around the reference and casting as in line 4.

  • ((Parent)childRef).childMethod(); //line 8 - Reason: By casting as Parent, we are telling java to treat the reference as Parent; so java will treat the reference as Parent, and you cannot call a child method using a parent reference. 

Comments

Cool.  nice explanation about casting....

Was it useful?

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)