Java rules for casting

后端 未结 6 647
长发绾君心
长发绾君心 2020-12-01 03:25

When can a certain object be cast into another object? Does the casted object have to be a subtype of the other object? I\'m trying to figure out the rules...

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 03:32

    This will work:

    class Foo implements Runnable {
        public void run() {}
    }
    
    Foo foo = new Foo();
    System.out.println((Runnable) foo);
    

    But this will not:

    class Bar {
        public void run() {}
    }
    
    Bar bar = new Bar();
    System.out.println((Runnable) bar);
    

    Because although Bar has a run() method that could implement Runnable.run(), Bar is not declared to implement Runnable so it cannot be cast to Runnable.

    Java requires that you declare implemented interfaces by name. It does not have duck typing, unlike some other languages such as Python and Go

提交回复
热议问题