Vaibhav Raj
Vaibhav Raj

Reputation: 2232

Java Language Specification: meaning of notation |S|

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.

Upvotes: 7

Views: 315

Answers (2)

Daniel Le
Daniel Le

Reputation: 1830

4.6. Type Erasure

We write |T| for the erasure of type T.

Hence |S| is the erasure of type S.

Upvotes: 0

mrak
mrak

Reputation: 2906

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>();
    }

Upvotes: 3

Related Questions