Type Casting Example Program

This section provides a tutorial example on how to use up casting and down casting explicitly and implecitly.

Now let's see a tutorial example program that uses up casting and down casting explicitly and implicitly:

/* TypeCasting.java
 - Copyright (c) 2014, HerongYang.com, All Rights Reserved.
 */
class TypeCasting {
   public static void main(String[] a) {
      java.io.PrintStream o = System.out;

      // getting an object of reference type: Thread
      Thread alarmThread = new Thread();
      
      // explicit up casting to Object
      Object alarmObject = (Object) alarmThread;

      // explicit down casting to Runnable
      Runnable alarmRunnable = (Runnable) alarmObject;

      // explicit down casting to Thread
      Thread copyThread = (Thread) alarmRunnable;

      // implicit up casting to Runnable
      Runnable copyRunnable = copyThread;
      
      o.println("alarmThread = "+alarmThread);
      o.println("alarmObject = "+alarmObject);
      o.println("alarmRunnable = "+alarmRunnable);
      o.println("copyThread = "+copyThread);
      o.println("copyRunnable = "+copyRunnable);
   }
}

Compile and run the example, you will get:

alarmThread = Thread[Thread-0,5,main]
alarmObject = Thread[Thread-0,5,main]
alarmRunnable = Thread[Thread-0,5,main]
copyThread = Thread[Thread-0,5,main]
copyRunnable = Thread[Thread-0,5,main]

As you can see, all up castings and down castings are valid, because the reference object "new Thread()" is compatible with Object, Runnable, and Thread.

Last update: 2014.

Table of Contents

 About This Book

 Installing JDK 1.8 on Windows

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

Reference Data Types and Variables

 Reference Types Supported in Java

 Creating Class Type Objects

 Class Type Variables Storing References

 Interface Type Variables

 Class and Interface Hierarchy

 Supertype and Subtype

 Explicit and Implicit Type Casting

Type Casting Example Program

 Type Casting Compile and Runtime Error

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Outdated Tutorials

 References

 PDF Printing Version