Hacker News new | ask | show | jobs
by skn0tt 2488 days 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.

1 comments

Oh right, I totally forgot about casting to Object! So much for "sort of sound" haha