Java Tutorials - Herong's Tutorial Examples - v8.22, by Herong Yang
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
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
Class Type Variables Storing References
Explicit and Implicit Type Casting
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
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