Type Casting Example Program

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

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

/* TypeCasting.java
 * Copyright (c) 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.

Table of Contents

 About This Book

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 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

 Enum Types and Enum Constants

 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

 Java Modules - Java Package Aggregation

 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

 Assert Statements and -ea" Option

 Annotation Statements and Declarations

 Java Related Terminologies

 Archived Tutorials

 References

 Full Version in PDF/EPUB