Reputation: 2210
When doing this, I get this error:
The return type is incompatible with MouseAdapter.mouseClicked(MouseEvent)
Class:
public class MyMouseAdapter extends MouseAdapter
{
public MyMouseAdapter()
{
// TODO Auto-generated constructor stub
}
@Override
public String mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
}
}
Where is that wrong? The original method is public void mouseClicked(MouseEvent e)
Upvotes: 0
Views: 1867
Reputation: 4272
When overriding a method, it must be done in a way that the subclass absolutely represents it's parent. In this case, you're overriding mouseClicked(MouseEvent e)
, which isn't allowed return anything; it's a void
method. So, firstly, to get around this problem you need to change your implementation to:
public void mouseClicked(MouseEvent e) {
/** Do stuff. **/
}
The reason you're not allowed to change the return type of the method is because when subclassing a parent class, you're saying that the subclass can be interacted with in the exact same way as it's parent. So, if you had an array of objects which all inherit from the same parent, you can treat them all in this generic fashion; you know they all return no data when their mouseClick
method is called.
Hypothetically speaking, if some implementations of this class returned a String
when the mouse is clicked, and some didn't, how would a generic interaction with the array of these subclasses be able to tell the difference? This is where the power of Object Oriented programming comes into play; you can interact with instances of a MouseAdapter
in a generic fashion, and allow them to override this method in their own class-specific way.
You can work around this by adding some methods to the class which can be called from the mouseClicked(MouseEvent e)
method, which would allow you to handle your String
data. This would ensure interaction with your subclass in a specific way, after handling the generic input event.
Upvotes: 5