1.局部内部类例子
实现:控制台输出:
|
1
2
|
现在开始销售苹果
单价为:
100
元
|
详细代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package
com.lixiyu;
public
class
SellOutClass {
private
String name;
//私有成员变量
public
SellOutClass(){
name=
"苹果"
;
}
public
void
sell(
int
price){
class
Apple{
//局部内部类
int
innerPrice=
0
;
public
Apple(
int
price){
innerPrice=price;
}
public
void
price(){
System.out.println(
"现在开始销售"
+name);
System.out.println(
"单价为:"
+innerPrice+
"元"
);
}
}
Apple apple=
new
Apple(price);
//实例化Apple类的对象
apple.price();
//调用局部内部类的方法
}
public
static
void
main(String[] args){
SellOutClass sample=
new
SellOutClass();
//实例化SellOutClass类的对象
sample.sell(
100
);
//调用selloutclass类的sell方法
}
}
|
————————
2.简单闹钟应用
实现:控制台不断输出当前时间,并每隔一秒会发出提示音。用户可以单击“确定”退出程序
效果图:
详细代码:
主程序部分:
|
1
2
3
4
5
6
7
8
9
10
|
package
com.lixiyu;
import
javax.swing.JOptionPane;
public
class
PartArea {
public
static
void
main(String[] args){
AlarmClock clock=
new
AlarmClock(
1000
,
true
);
clock.start();
JOptionPane.showMessageDialog(
null
,
"是否退出?"
);
System.exit(
0
);
}
}
|
实现AlarmClock部分,运用到局部内部类方法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package
com.lixiyu;
import
java.awt.Toolkit;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.text.SimpleDateFormat;
import
java.util.Date;
import
javax.swing.Timer;
public
class
AlarmClock {
private
int
delay;
private
boolean
flag;
public
AlarmClock(
int
delay,
boolean
flag){
//局部内部类
this
.delay=delay;
this
.flag=flag;
}
public
void
start() {
// TODO Auto-generated method stub
class
Printer
implements
ActionListener {
@Override
public
void
actionPerformed(ActionEvent e) {
SimpleDateFormat format =
new
SimpleDateFormat(
"k:m:s"
);
String result = format.format(
new
Date());
System.out.println(
"当前的时间是:"
+ result);
if
(flag) {
Toolkit.getDefaultToolkit().beep();
}
}
}
new
Timer(delay,
new
Printer()).start();
}
}
|
本文转自lixiyu 51CTO博客,原文链接:http://blog.51cto.com/lixiyu/1304680,如需转载请自行联系原作者
