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:

SLList<Integer> sl = new VengefulSLList<Integer>();
  • Compile-time type of right hand side (RHS) expression is VengefulSLList.

  • A VengefulSLList is-an SLList, so assignment is allowed.

VengefulSLList<Integer> vsl = new SLList<Integer>();
  • 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.

public static Dog maxDog(Dog d1, Dog d2) { … }
  • Any call to maxDog will have compile-time type Dog!

Example:

Poodle frank  = new Poodle("Frank", 5);
Poodle frankJr = new Poodle("Frank Jr.", 15);

Dog largerDog = maxDog(frank, frankJr);
Poodle largerPoodle = maxDog(frank, frankJr);
  • 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