2

I wonder if there is any way to avoid unnecessary methods from implemented interface or other class.
Let say that I have simple class implementing MouseListener, when actually I need only one method mousePressed( MouseEvent e) to override. However, in that case I also have to override every other method from interface but keep them empty like that:

public void mouseExited( MouseEvent e) {}
public void mouseClicked( MouseEvent e) {}
public void mouseReleased( MouseEvent e) {}
public void mouseEntered( MouseEvent e) {}

Is there any tricky solution to override only method I really need even when the others are abstract in interface/superclass and still keep my class as non-abstract?

2 Answers 2

8

Extend MouseAdapter. It implements MouseListener by doing nothing for every method. So you can just override the one that you want.

Sign up to request clarification or add additional context in comments.

4 Comments

But what if I need to extend some other class and implement a couple of interfaces?
You can implement an infinite number of interfaces but you can only inherit from one class. So you have to make a choice.
On top of that, if you want to be able to do this for any other interface you can make a dummy class that implements all of the interface methods (and does nothing with them) and then extend that class. I wouldn't recommend doing so though.
Maybe the MouseListener is trying to do too much if it needs to extend a class other than MouseAdapter and implement a couple of interfaces. Remember you can give it a constructor that takes a reference parameter, so it have have a has-a relationship to some other object.
1

The solution of JB Nizet is good but by the way why it is a problem ? with modern IDE like Eclipse you can add all methods to implement with just one click (source > override/implement method). If you use an adapter it's practical but you can't extend another class than the adapter.

1 Comment

I was only wondering how to avoid unnecessary code whom I didn't use at all, but need to place in my classes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.