java - Confusing method bindings -
the output of simple program this base
.
public class mainapp{ private void func(){ system.out.println("this base"); } public static void main(string[] args){ mainapp newobj = new derived(); newobj.func(); } } class derived extends mainapp{ public void func(){ system.out.println("this derived"); } }
my question when using line
mainapp newobj = new derived();
not creating object of derived class using reference of base class mainapp. so, when using object call it's method why don't method derived class? why method base class.using line,
mainapp newobj = new derived();
, working reference of mainapp or working object of derived class. 1 correct?
the reason you're getting base class method base class version of func
declared private
, , java not allow private methods overridden subclasses. means if extend base class , pure coincidence decide name private member function same name private member function in base class, don't accidentally change behavior of base class's member functions. indeed working object of type derived
, because reference statically typed mainapp
, calling func
interpreted calling private method func
in mainapp
rather public method func
in derived
. changing code read
derived d = new derived(); d.func();
fixes this, because static type of d
derived
, call func
has different meaning.
at jvm bytecode level, instruction used call private member functions invokespecial
whereas instruction used call normal, override-able member functions invokevirtual
. 2 have totally different semantics; invokespecial
begins looking in current class (or base class things constructors), whereas invokevirtual
looks in class corresponding object's type @ runtime.
Comments
Post a Comment