I am going through the JLS 7 to understand the type casting Section 5.5.1.
It says: Given a compile-time reference type S (source) and a compile-time reference type T (target), a casting conversion exists from S to T if no compile-time errors occur due to the following rules. If S is a class type:
They made it clear if S and T are two types in Section 4.10, then
I am not able to find the meaning of |S|. Please help me understand what does it mean by |S|? Does it mean the number and types of properties or something else. I tried to search for it in JLS itself but couldn't find it's meaning. Thanks in advance.
The Java® programming language is a general-purpose, concurrent, class-based, object-oriented language.
It describes all aspects of the language, including the semantics of all types, statements, and expressions, as well as threads and binary compatibility.
Written by the inventors of the technology, The Java Language Specification, Java SE 8 Edition is the definitive technical reference for the Java programming language. The book provides complete, accurate, and detailed coverage of the Java programming language.
I'm not able to provide better and less formal explanation that the doc for type erasure. In your case (Class casting) "If T is a class type, then either |S| <: |T|, or |T| <: |S|. Otherwise, a compile-time error occurs." means, that after type erasure a class cast is legal if the generic type arguments are in "class-subclass relationship". Simple example for that:
static class Bar {}
static class FooBar extends Bar {}
public static void main(String[] args) {
List<FooBar> foobarList = (List<FooBar>) newList(Bar.class);
List<Bar> barList = (List<Bar>) newList(FooBar.class);
System.out.println("No cast class exception :)");
}
private static<T> List<?> newList(Class<T> clazz) {
return new ArrayList<T>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With