Type Casts


Type Casts

🙋 Need help? Ask an expert now!

Do you remember casting int and double data types? "Type Casts" are similar to casting but for objects.

The syntax for type casts is as follows, (requiredType)(expression/variable).

Something to remember when type casting objects is whether or not the class is a "descendant" of another one class (has a parent class). If so, we can create objects that incorporate two different classes. We will look at the concept of inheritance later in the course. For now, keep in mind that every single class is a "descendant" of a class called Object that exists in the package java.lang (automatically-imported), so you can create objects like the one below.

package exlcode;

public class TypeCastExample {

  public static void main(String[] args) {
    Object exampleVariableOne = new TypeCastTest();
    // exampleVariableOne has to be casted to a TypeCastTest object
    // before accessing language
package exlcode;

public class TypeCastTest {

  public String language = "Java";

When we call Object exampleVariableOne = new TypeCastTest(), exampleVariableOne becomes an instance of both Object and TypeCastTest. Even though this is allowed in Java, you can't actually call a method or access a variable from the TypeCastTest class because you have to specify which instance you are referring to when attempting to access any members of a class. The solution is to cast exampleVariableOne to a TypeCastTest so that the program sees which class you are referring to and accesses the members from the right class.

This is one of the more complex ideas in object-oriented programming, but will be crucial when we dive into inheritance and interface later in the course.

Edit Me on GitHub!

Application Question

Consider the following code:

String varOne = "Welcome to Java";
Object varTwo = varOne;
String varThree = (String)varTwo;

Which of the following statements is true?