Adapter Class: Are Classes From Java - Awt.event Package
Adapter Class: Are Classes From Java - Awt.event Package
ComponentListener ComponentAdapter
ContainerListener ContainerAdapter
FocusListener FocusAdapter
KeyListener KeyAdapter
MouseListener MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter
Here's a mouse adapter that beeps when the mouse is clicked
import java.awt.*;
import java.awt.event.*;
public class MouseBeeper extends MouseAdapter
{
public void mouseClicked(MouseEvent evt)
{
Toolkit.getDefaultToolkit().beep();
}
}
Without extending the MouseAdapter class, I would have had to write the same class like this
import java.awt.*;
import java.awt.event.*;
public class MouseBeeper implements MouseListener
{
public void mouseClicked(MouseEvent evt)
{
Toolkit.getDefaultToolkit().beep();
}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
Inner Classes
Inner classes are a security mechanism in Java.
Inner class is a class defined inside other class
and act like a member of the enclosing class.
Unlike a class, an inner class can be private
and once you declare an inner class private, it
cannot be accessed from an object outside
the class.
class Outer_Demo
{
int num;
//inner class
private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class");
}
}
//Accessing the inner class from the method within the outer class
void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class
{
public static void main(String args[])
{
//Instantiating the outer class
Outer_Demo outer=new Outer_Demo();
outer.display_Inner();
}
}
Inner classes are of three types depending on
how and where you define them. They are:
– Inner Class
– Method-local Inner Classes
– Anonymous Inner Class
Method-local Inner Class
When an inner class is defined inside the
method of Outer Class it becomes Method
local inner class.
Method local inner class can be instantiated
within the method where it is defined and no
where else.
Method local inner class can only be declared
as final or abstract.
Method local class can only access global
variables or method local variables if declared
as final.
public class Outerclass
{
//instance method of the outer class
void my_Method()
{
int num=23;
//method-local inner class
class MethodInner_Demo
{
public void print()
{
System.out.println("This is method inner class "+num);
}
}//end of inner class