i trying head around dynamic method invoking in java , not able understand why java not let me invoke method subclass instead of method of superclass.
for example: if have 2 classes test
, test2
. test2 inherits class test
the method somefunction()
overridden in subclass:
test class
public class test { public test(){ system.out.println("i test class constructor called no values"); } public void somefunction(){ system.out.println("i function belonging test class"); } }
and test2 class:
public class test2 extends test{ public test2(){ system.out.println("constructor of test2 no values"); } public void somfunction(){ system.out.println("i somefunction overridden in test2"); } }
so when try instantiate test class in way:
test t1 = new test2(); t1.somefunction(); // should call test2.somefunction()
the output is:
i test class constructor called no values constructor of test2 no values function belonging test class
so question is: when call method somefunction()
using object t1
why invoke method belong superclass instead 1 in subclass when initializing object subclass.
thought dynamic invoking used work in way class initialize object with, methods of class called i.e overridden method should called instead of parent method.
dinesh
typo.
public void somfunction(){
should be
public void somefunction(){
as leonbloy says in comments, if place annotation @override before method, compiler compile-time check overrides something. if method name typo (or if method overrides changes signature) not compile:
@override public void somfunction(){ //compile time error
Comments
Post a Comment