Java/Class/Anonymous class
Содержание
Access inner class from outside
<source lang="java">
public class Main {
public static void main(String[] args) { Outer outer = new Outer(); outer.new Inner().hello(); }
} class Outer {
public class Inner { public void hello(){ System.out.println("Hello from Inner()"); } }
}
</source>
an example of a simple anonymous class
<source lang="java">
public class MainClass {
public static void main(String[] args) { Ball b = new Ball() { public void hit() { System.out.println("You hit it!"); } }; b.hit(); } interface Ball { void hit(); }
}
</source>
Anonymous inner class
<source lang="java">
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class SimpleEvent {
public static void main(String[] args) { JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); JFrame f = new JFrame(); f.add(close); f.setSize(300, 200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }
}
</source>
Tick Tock with an Anonymous Class
<source lang="java">
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.Timer; public class MainClass {
private String tickMessage = "Tick..."; private String tockMessage = "Tock..."; public static void main(String[] args) { TickTockAnonymous t = new TickTockAnonymous(); t.go(); } private void go() { Timer t = new Timer(1000, new ActionListener() { private boolean tick = true; public void actionPerformed(ActionEvent event) { if (tick) { System.out.println(tickMessage); } else { System.out.println(tockMessage); } tick = !tick; } }); t.start(); JOptionPane.showMessageDialog(null, "Click OK to exit program"); System.exit(0); }
}
</source>