In: Computer Science
What is wrong with the following code? Give two effective ways to fix it.
1 import javax.swing.*;
2 import java.awt.event.*;
3
4 public class H2ClassJ extends JFrame {
5 public static final long serialVersionUID = 22;
6
7 public H2ClassJ () {
8 addMouseListener (new MouseListener () {
9 public void mouseClicked (MouseEvent e) {}
10 });
11 } // end constructor
12
13 } // end class H2ClassJ
Abstract class in Java is like interface aside from that it can contain default method usage. An abstract class can have an abstract method without body and it can have methods with usage too.
MouseListener is a class of this type. This means, to use this and implement this we need to bypass(override) this in the class itself, so that methods can be implemented.
2 effective ways to fix this:-
1.
we need to create the overriden methods of the class that we overrided ie. MouseListner. This ensures there is no anomaly of classes in the code.:-
new MouseListener (){
@Override
public void mouseEntered(MouseEvent arg) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mouseClicked (MouseEvent e) {}
@Override
public void mouseExited(MouseEvent arg0) {}
}
2.
implement a new Adapter that is mouse adapter. Now methods can be declared as per ease of the user which is an effective way of implementing this,
public H2ClassJ ()
{addMouseListener (
new MouseAdapter ()
{public void mouseClicked (MouseEvent e)
{}
}
);