0

Is there a way to use casting so the m1() method is run in I1 class to print In I1 class? I don't want it to run the 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();
    }
chiastic-security
  • 20,430
  • 4
  • 39
  • 67
Mel
  • 59
  • 2
  • 8
  • I thought ((I1)tc).m1(); would work, but it still prints "Hello" – Mel Oct 02 '15 at 20:11
  • No, that would be big security flaw. Similar question explaining why `super.super` is also impossible: http://stackoverflow.com/questions/586363/why-is-super-super-method-not-allowed-in-java – Pshemo Oct 02 '15 at 20:11
  • You can't do that. [Here][1] is the explanation why. [1]: http://stackoverflow.com/a/22874698/4228138 – Mateusz Korwel Oct 02 '15 at 20:22
  • @MateuszKorwel Nice find. Anyway if you want to post links in comments simply use `[description](link)`. – Pshemo Oct 02 '15 at 20:24

2 Answers2

2

No, you can't do this. Part of the point of polymorphism is to be able to hide implementation detail from classes lower down in the hierarchy. You can invoke the superclass method, but only as a call inside the overridden method.

Think about it like this. Maybe TestClass does something important inside method m1 that maintains its internal state and keeps it consistent. Perhaps it tracks something that's done in the superclass, and maintains its own cache, or copy, or similar. If you could make it invoke the superclass method, that code wouldn't get run, and you'd break TestClass badly.

The reason that the suggestion in your comment

((I1)tc).m1();

doesn't work is that you've changed the formal type but not the actual type. Invocation of overridden methods is based on the actual type, at runtime, so the JVM will still notice that this is of type TestClass, and invoke the overridden method.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
0

You first declared I1 tc = new TestClass(), so even you do ((I1)tc).m1(), tc is still pointing to an object of TestClass(). Thats why it wouldn't work.

If you want to call m1() from the I1 class, you should do I1 tc = new I1(); instead.

OPK
  • 4,120
  • 6
  • 36
  • 66