Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can't cast from a HashMap to an Animal class in Java, so in that sense Java is sounder. But you can still do `Animal a = null; a.walk();`, so in that sense, Java isn't sound.


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.


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




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: