1. 程式人生 > >Java核心技術--內部類

Java核心技術--內部類

1.內部類

 1 package innerClass;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import java.util.*;
 6 import javax.swing.*;
 7 import javax.swing.Timer;
 8 
 9 /**
10  * This program demonstrates the use of inner classes.
11  * @version 1.11 2015-05-12
12  * @author Cay Horstmann
13  */
14 public
class InnerClassTest 15 { 16 public static void main(String[] args) 17 { 18 TalkingClock clock = new TalkingClock(1000, true); 19 clock.start(); 20 21 // keep program running until user selects "Ok" 22 JOptionPane.showMessageDialog(null, "Quit program?"); 23 System.exit(0);
24 } 25 } 26 27 /** 28 * A clock that prints the time in regular intervals. 29 */ 30 class TalkingClock 31 { 32 private int interval; 33 private boolean beep; 34 35 /** 36 * Constructs a talking clock 37 * @param interval the interval between messages (in milliseconds) 38 * @param
beep true if the clock should beep 39 */ 40 public TalkingClock(int interval, boolean beep) 41 { 42 this.interval = interval; 43 this.beep = beep; 44 } 45 46 /** 47 * Starts the clock. 48 */ 49 public void start() 50 { 51 ActionListener listener = new TimePrinter(); 52 Timer t = new Timer(interval, listener); 53 t.start(); 54 } 55 56 public class TimePrinter implements ActionListener 57 { 58 public void actionPerformed(ActionEvent event) 59 { 60 System.out.println("At the tone, the time is " + new Date()); 61 if (beep) Toolkit.getDefaultToolkit().beep(); 62 } 63 } 64 }

2.匿名內部類

 1 package anonymousInnerClass;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import java.util.*;
 6 import javax.swing.*;
 7 import javax.swing.Timer;
 8 
 9 /**
10  * This program demonstrates anonymous inner classes.
11  * @version 1.11 2015-05-12
12  * @author Cay Horstmann
13  */
14 public class AnonymousInnerClassTest
15 {
16    public static void main(String[] args)
17    {
18       TalkingClock clock = new TalkingClock();
19       clock.start(1000, true);
20 
21       // keep program running until user selects "Ok"
22       JOptionPane.showMessageDialog(null, "Quit program?");
23       System.exit(0);
24    }
25 }
26 
27 /**
28  * A clock that prints the time in regular intervals.
29  */
30 class TalkingClock
31 {
32    /**
33     * Starts the clock.
34     * @param interval the interval between messages (in milliseconds)
35     * @param beep true if the clock should beep
36     */
37    public void start(int interval, boolean beep)
38    {
39       ActionListener listener = new ActionListener()
40          {
41             public void actionPerformed(ActionEvent event)
42             {
43                System.out.println("At the tone, the time is " + new Date());
44                if (beep) Toolkit.getDefaultToolkit().beep();
45             }
46          };
47       Timer t = new Timer(interval, listener);
48       t.start();
49    }
50 }

第二種方法比第一種更為簡潔,多年來,Java程式設計師習慣的做法是用匿名內部類實現事件監聽器和其他回撥。

上述兩種方法可以用lambda來實現,更為簡潔

1 public void start(int interval, boolean beep) {
2         Timer t = new Timer(interval, event -> {
3             System.out.println("At the tone, the time is " + new Date());
4             if (beep) Toolkit.getDefaultToolkit().beep();
5         });
6         t.start();
7 }

3.匿名內部類的一個使用技巧--“雙括號初始化”

假設你想構造一個數組列表,並將它傳遞到一個方法:

1 ArrayList<String> friends = new ArrayList<>();
2 friends.add("Harry");
3 friends.add("Tony");
4 invite(friends);

如果不在需要這個陣列列表,最好讓他作為一個匿名列表,方法如下:

invite(new ArrayList<String>() {{ add("Harrry"); add("Tony"); }});

外層括號建立了ArrayList的一個匿名子類,內層括號則是一個物件構造塊。