10.3 Casting
Dynamic Method Selection and Type Checking Puzzle
Static vs. Dynamic Type Reminder: Every variable in Java has a static type. This is the type specified when the variable is declared, and is checked at compile time. Every variable also has a dynamic type; this type is specified when the variable is instantiated, and is checked at runtime.
Compile-Time Type Checking and Expressions
Compiler allows method calls based on compile-time type of variable. The compiler also allows assignments based on compile-time types.
Expressions have compile-time types:
An expression using the new keyword has the specified compile-time type. Example:
Compile-time type of right hand side (RHS) expression is VengefulSLList.
A VengefulSLList is-an SLList, so assignment is allowed.
Compile-time type of RHS expression is SLList.
An SLList is not necessarily a VengefulSLList, so compilation error results.
Expressions have compile-time types:
Method calls have compile-time type equal to their declared type.
Any call to maxDog will have compile-time type Dog!
Example:
Compilation error! RHS has compile-time type Dog
Casting
Java has a special syntax for specifying the compile-time type of any expression.
Put desired type in parenthesis before the expression.
Tells compiler to pretend it sees a particular type.
Casting is a powerful but dangerous tool.
Tells Java to treat an expression as having a different compile-time type.
In example below, effectively tells the compiler to ignore its type checking duties.
Does not actually change anything: sunglasses don’t make the world dark.
Last updated