3 ms·
That's not correct. Java method dispatch is always dynamic, so x.foo() will always call the foo() method on whatever concrete type x actually is. The declared t
by koreth1 7y ago
That's not correct. Java method dispatch is always dynamic, so x.foo() will always call the foo() method on whatever concrete type x actually is. The declared type of the variable that holds the reference to that object doesn't matter, nor does casting (with a couple exceptions, none of which apply here).
But don't trust me, try it!
| Welcome to JShell -- Version 11.0.5
| For an introduction type: /help intro
jshell> class Foo { void foo() { System.out.println("Super"); } }
| created class Foo
jshell> class Bar extends Foo { void foo() { System.out.println("Sub"); } }
| created class Bar
jshell> Foo f = new Bar();
f ==> Bar@58651fd0
jshell> Bar b = new Bar();
b ==> Bar@5419f379
jshell> f.foo();
Sub
jshell> b.foo();
Sub
jshell> ((Foo)b).foo();
Sub
- frant-hartm 7y agoThat's right, I forgot a method parameter: jshell> class Foo { void foo(Object o) { System.out.println("Super"); } } | created class Foo jshell> class Bar extends Foo { void foo(Integer i) { System.out.println("Sub"); } } | created class Bar jshell> Foo f = new Bar(); f ==> Bar@7f9a81e8 jshell> Integer i = 1; i ==> 1 jshell> f.foo(i) Super jshell> ((Bar)f).foo(i); Sub