这个例子是一个多线程的小程序,这里面就应用到了匿名内部类,实现了Runnable接口。 匿名内部类的一般好处是:是代码更加简洁,紧凑,但带来的是易读性下降。他一般用在GUI编程中 实现事件处理等等。希望大家一起讨论public class RunnableTest{ public static void main(String[] args){ MyThread1 mt1 = new MyThread1(); MyThread2 mt2 = new MyThread2(); MyThread3 mt3 = new MyThread3(); mt2.th.start(); mt1.th.start(); mt3.th.start(); } }class MyThread1 implements Runnable{ Thread th = new Thread(this); public void run(){ for (int i = 0; i < 10; i++){ System.out.println("BMW" + i); } } }class MyThread2{ Thread th = new Thread(){ public void run(){ for (int i = 0; i < 10; i++){ System.out.println(i); } } }; } class MyThread3{ Runnable ra = new Runnable(){ public void run(){ for (char ch = 65; ch < 70; ch++){ System.out.println(ch); } } }; Thread th = new Thread(ra); }
匿名内部类可以访问外部类的私有成员,其他的方式实现接口和继承类做不到 实现方式: SuperType aa = new SuperType(construction parameters){methods and data} 或 InterfaceType aa = new InterfaceType(){methods and data} 具体实现时需要把SuperType 和InterfaceType 换成具体的超类和接口。
匿名内部类的一般好处是:是代码更加简洁,紧凑,但带来的是易读性下降。他一般用在GUI编程中
实现事件处理等等。希望大家一起讨论public class RunnableTest{
public static void main(String[] args){
MyThread1 mt1 = new MyThread1();
MyThread2 mt2 = new MyThread2();
MyThread3 mt3 = new MyThread3();
mt2.th.start();
mt1.th.start();
mt3.th.start();
}
}class MyThread1 implements Runnable{
Thread th = new Thread(this);
public void run(){
for (int i = 0; i < 10; i++){
System.out.println("BMW" + i);
}
}
}class MyThread2{
Thread th = new Thread(){
public void run(){
for (int i = 0; i < 10; i++){
System.out.println(i);
}
}
};
}
class MyThread3{
Runnable ra = new Runnable(){
public void run(){
for (char ch = 65; ch < 70; ch++){
System.out.println(ch);
}
}
};
Thread th = new Thread(ra);
}
实现方式:
SuperType aa = new SuperType(construction parameters){methods and data}
或
InterfaceType aa = new InterfaceType(){methods and data}
具体实现时需要把SuperType 和InterfaceType 换成具体的超类和接口。
我觉得匿名的应该是隐藏实现,而且用完就out的那种。