Sumit Kumar
Sumit Kumar

Reputation: 781

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

Upvotes: 1

Views: 85

Answers (2)

Sanjeev Saha
Sanjeev Saha

Reputation: 2652

Please see the link: https://en.wikipedia.org/wiki/Method_overriding

It is said that:

The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.

To the variable named IMRobos you assigned an object of super class i.e. IMROBOS so you got the behavior of super class but if you had assigned the object of sub class i.e. testC, you would have got the behavior of sub class.

Upvotes: 0

Eran
Eran

Reputation: 394146

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

Upvotes: 1

Related Questions