Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Interface casting

Tags:

I stumbled across a Java casting situation involving Generics and Interfaces that I do not understand.

Please consider the following code where I create a List<Interface1>. And then get() an element and cast it to Interface2 without compiler error although these two interfaces are completely unrelated.

import java.util.*;

public class Main {
  public static void main(String ... args) {
    List<Interface1> list = new ArrayList<>();
    list.add(new Interface1() {});

    Interface1 ok = list.get(0);
    Interface2 why = (Interface2)list.get(0);
  }
}

interface Interface1 {
}

interface Interface2 {
}

Can anyone explain why there is not compiler error for the cast at the second get(0)?

Two side notes: Executing the class throws a ClassCastException (as expected). And using two classes instead of interfaces does actually generate compile errors.

like image 736
Quota Avatar asked Mar 25 '14 10:03

Quota


People also ask

Can you cast generic type java?

The Java compiler won't let you cast a generic type across its type parameters because the target type, in general, is neither a subtype nor a supertype.

Do generics prevent type cast errors?

Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.

Can we use generics in interface?

Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods.


1 Answers

This behaviour is unrelated to generics: you can cast any interface to any other without compile errors.

You cannot do this with classes because Java can check at compile time whether one class can be casted to another.

With interfaces however the cast might succeed or fail, depending on the class that is actually implementing the interface. This can be discovered only at runtime though.

like image 199
Flavio Avatar answered Nov 02 '22 07:11

Flavio