java - How to cast to run superclass method -


is there way use casting m1() method run in i1 class print in i1 class? don't want run overridden method.

class testclass extends i1 implements i2{        public void m1() { system.out.println("hello"); }        public static void main(string[] args){           i1 tc = new testclass();           tc.m1();        }     }     class i1{        int value = 1;        public void m1(){system.out.println("in i1 class");}     }     interface i2{        int value = 2;        void m1();     } 

no, can't this. part of point of polymorphism able hide implementation detail classes lower down in hierarchy. can invoke superclass method, call inside overridden method.

think this. maybe testclass important inside method m1 maintains internal state , keeps consistent. perhaps tracks that's done in superclass, , maintains own cache, or copy, or similar. if make invoke superclass method, code wouldn't run, , you'd break testclass badly.

the reason suggestion in comment

((i1)tc).m1(); 

doesn't work you've changed formal type not actual type. invocation of overridden methods based on actual type, @ runtime, jvm still notice of type testclass, , invoke overridden method.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -