Sumit Kumar Sumit Kumar - 6 months ago 18
Java Question

java Overriding is not working

The method in the subClass "testC.java doesn't override the method in the superClass "IMROBOS.java"
I also do not get any errors or warnings, but they do not work as expected.
The output of the superClass method is displayed, and not of the one in the subClass. If I'm doing something wrong, then why am I not getting error messages?
A similar question was on stackoverflow and it mentioned that changing methods to "protected" worked, but not in my case.

Also, please tell me if I'm accessing the variable "roboKey" correctly in the testC.java?
Thanks

My superClass "IMROBOS.java"

import java.awt.event.*;
class IMROBOS extends KeyAdapter {
public int roboKey;
public char roboKeyChar;
@Override
public void keyPressed( KeyEvent event) {
roboKeyChar = event.getKeyChar();
roboKey = event.getKeyCode();
roboAction( roboKey );
}

protected void roboAction( int k ){
System.out.println( roboKey );
}

}


My subClass "testC.java":

import java.awt.event.KeyEvent;
class testC extends IMROBOS {
public static IMROBOS IMRobos = new IMROBOS();
@Override
protected void roboAction( int k ){
System.out.println( " SubClass: " + IMRobos.roboKey + " | " + k + " | " + IMRobos.roboKeyChar );
}

public static void main( String[] a ){
JFrame jframe = new JFrame();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.addKeyListener( IMRobos );
jframe.setSize(400, 350);
jframe.setVisible(true);
}
}

Answer

You are only creating and using an instance of the super-class :

public static IMROBOS IMRobos = new IMROBOS();
...
jframe.addKeyListener( IMRobos );

That's the reason the sub-class's roboAction is not called.

If you require the sub-class's method to be called, create an instance of the sub-class :

public static IMROBOS IMRobos = new testC ();

BTW, please use Java naming conventions (class names should be capitalized and variable and method names should use camel case). Your code would be more readable.

public static IMRobos iMRobos = new TestC ();