Sumit Kumar Sumit Kumar - 1 year ago 65
Java Question

java Overriding is not working

The method in the subClass " doesn't override the method in the superClass ""
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

My superClass ""

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

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


My subClass "":

import java.awt.event.KeyEvent;
class testC extends IMROBOS {
public static IMROBOS IMRobos = new IMROBOS();
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.addKeyListener( IMRobos );
jframe.setSize(400, 350);

Answer Source

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 ();