How does one make a method in an interface that’s not abstract? I know that it CAN be done, I just don’t know how.
I’ll give an example of my confusion. In Java you can implement java.awt.event.MouseListener, then you must call the method addMouseListener(Object)… passing your class as a parameter, so the MouseListener knows what object to cast from. How is the addMouseListener(Object) method possible?
Someone said I was confusing the way anonymous classes work with interfaces having non-abstract methods. How would you implement an anonymous class within a interface so the implementer can call its methods? I’m very new and still a ‘noob’ at OOP.
If you’re interested in anonymous inner classes, they work as shown below.
We’ll continue with the MouseListener example.
The interface for
java.awt.event.MouseListenerlooks something like this:Somewhere in your app you may want to respond to mouse events, so using an anonymous inner class you could do something like this.
What you’ve done here is created a new class (without name, hence anonymous) that implements the MouseListener interface. You have not, as suggested above, created a non-abstract method on an interface.
You could have also just created a new named class (“named class” means regular old class):
Then somewhere else you would do
component.addMouseListener(new MyMouseListener());See the difference?
I hope this helps. Good luck.
P.S. – Read up on inheritance, interfaces, inner classes and anonymous inner classes in Java for a deeper understanding.