5 ms·
Correct me if I'm mistaken: I think you can indeed cast from HashMap to Animal and it will happily compile: ```java import java.util.HashMap; class Main {
by skn0tt 7y ago
Correct me if I'm mistaken: I think you can indeed cast from HashMap to Animal and it will happily compile:
```java
import java.util.HashMap;
class Main {
class Animal {
String sound = "roar";
}
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
Animal animal = (Animal) (Object) map;
System.out.println(animal.sound);
}
}
```
At runtime, this will crash with the following Exception: `Exception in thread "main" java.lang.ClassCastException: class java.util.HashMap cannot be cast to class Main$Animal`, but it will satisfy the type system.
- lhorie 7y agoOh right, I totally forgot about casting to Object! So much for "sort of sound" haha