So I have two methods one in a superclass and one in a subclass with the same name and parameters lets say public void method(). I have also another method in the subclass called method1() as follows:
public void method1() {super.method();} The code above when executed it goes as planned (the method1 is using the method from the superclass) BUT if I change it to this:
public void method1() {((Class)this).method();} Where Class is the name of the superclass for some reason it does not use the superclass method but the method of the subclass with the same name. Isn't super the same thing with ((Class)this)? Why does this happen?
EDIT: This is the actual class (I added the actual code so my problem is more clear)
public class MWindow extends Window { private String message = "No message"; protected int size = 7; public MWindow(String message) { size = 2; this.message = message; System.out.println ("Window message = " + message); } public MWindow(int size, String message) { super(size); this.message = message; System.out.println ("Window message = " + message); } public void setSize1(int y) {size = y;} public void setSize2(int z) {super.setSize (z);} public void printSize() {System.out.println ("MSize="+size);} public void printSize1() {System.out.println(((Window)this).size);} public void printSize2() {((Window)this).printSize();} } This is the superclass
public class Window { protected int size; public Window() { size=1; System.out.println("Window size="+size); } public Window(int size) { this.size=size; System.out.println("Window size="+size); } public void setSize(int x) {size += x;} public void printSize() {System.out.println("Size=" + size);} } This is the main() class
public class RunWindow { public static void main (String[] args) { Window w1=new Window(); Window w2=new Window(2); System.out.println(w1.size); System.out.println(w2.size); MWindow mw1=new MWindow("First MWindow"); MWindow mw2=new MWindow(3, "Second MWindow"); System.out.println(mw1.size); System.out.println(mw2.size); mw1.setSize1(4); System.out.println(mw1.size); mw1.setSize2(2); System.out.println(mw1.size); mw1.setSize(2); System.out.println(mw1.size); w1.printSize(); mw1.printSize(); mw1.printSize1(); mw1.printSize2(); } } Executing the above we get:
Window size=1 Window size=2 1 2 Window size=1 Window message = First MWindow Window size=3 Window message = Second MWindow 2 7 4 4 4 Size=1 MSize=4 5 MSize=4 The problem is that at the last result it should be Size=5 instead of MSize=4 since the superclass printSize method is called and not the printSize method of the subclass.