What is the difference between a compile time type vs run time type for any object in Java?
Java is a statically typed language, so the compiler will attempt to determine the types of everything and make sure that everything is type safe. Unfortunately static type inference is inherently limited. The compiler has to be conservative, and is also unable to see runtime information. Therefore, it will be unable to prove that certain code is typesafe, even if it really is.
The run time type refers to the actual type of the variable at runtime. As the programmer, you hopefully know this better than the compiler, so you can suppress warnings when you know that it is safe to do so.
For example, consider the following code (which will not compile)
public class typetest{
public static void main(String[] args){
Object x = args;
String[] y = x;
System.out.println(y[0])
}
}
The variable x
will always have type String[]
, but the compiler isn't able to figure this out. Therefore, you need an explicit cast when assigning it to y
.
An example
Number x;
if (userInput.equals("integer")) {
x = new Integer(5);
} else {
x = new Float(3.14);
}
There are two types related to x
- the type of the name
x
. In the example, it'sNumber
. This is determined at compile-time and can never change, hence it's the static type - the type of the value
x
refers to. In the example, it can beInteger
orFloat
, depending on some external condition. The compiler cannot know the type at compilation time. It is determined at runtime (hence dynamic type), and may change multiple times, as long as it's a subclass of the static type.