java - How is the code flows in method overriding -
for below code got output
in base.foo() in derived.bar()
code:
class base { public static void foo(base bobj) { system.out.println("in base.foo()"); bobj.bar(); } public void bar() { system.out.println("in base.bar()"); } } class derived extends base { public static void foo(base bobj) { system.out.println("in derived.foo()"); bobj.bar(); } public void bar() { system.out.println("in derived.bar()"); } } class overridetest { public static void main(string []args) { base bobj = new derived(); bobj.foo(bobj); } }
how code flows? how getting output above. confused little bit , looking explanation.
static methods not overridden, there's no virtual invocation.
in derived
class, static foo
method hiding parent class' static foo
method.
however, in main
method, invoking foo
on reference type base
, hence base#foo
gets invoked (so prints "in base.foo()"
).
in turn, static method invokes bar
on passed object, is-a base
, happens instance of derived
.
since bar
instance method , is overridden given signature matches, invocation resolves instance type, derived
, hence "in derived.bar()"
printed.
notes
- a practice employ
@override
annotation on overridden methods. fail compilefoo
method it's static, pointing out there's no possible overriding there. - another practice (as pointed out jon skeet) avoid invoking
static
methods on instance objects (i.e. prefer explicitclassname.staticmethod
idiom), may cause confusion on scope in method invoked.
Comments
Post a Comment