标签:
分别写了一个匿名内部类和静态内部类的程序,局部内部类感觉就是后两者的一般情况,后两者则是前者的特殊应用。
局部内部类:在一个方法中定义一个类,不可以用public或static进行声明,可以对外部完全隐藏,只有该方法可以调用。
匿名内部类:不用写类的定义头部分,直接写类体,我个人感觉不太好,只有在接口要定义函数时用比较好吧?这种类不能有构造函数,所以它调用超类的构造函数,注意在内部类实现接口时不能有参数。
静态内部类:如果只是单存为了隐藏一个类,而不用内部类去调用外围对象,则可以用这种类,用起来有点像是Arrays.sort()。
package staticInnerClass;
public class StaticInnerCLassTest
{
public static void main(String[] args)
{
double[] d=new double[20];
for(int i=0;i<20;i++)
d[i]=100*Math.random();
ArrayAlg.Pair p=ArrayAlg.minmax(d);
System.out.println(p.GetFirst());
System.out.println(p.GetSecond());
}
}
class ArrayAlg
{
public static class Pair
{
private double first;
private double second;
public Pair(double first,double second)
{
this.first=first;
this.second=second;
}
public double GetFirst()
{
return this.first;
}
public double GetSecond()
{
return this.second;
}
}
public static Pair minmax(double[] value)
{
double min=Double.MAX_VALUE;
double max=Double.MIN_VALUE;
for(double v:value)
{
if(min>v)
min=v;
if(max<v)
max=v;
}
return new Pair(min,max);
}
}
package anonymousInnerClass;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class AnonymousInnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock=new TalkingClock();
clock.start(1000,true);
JOptionPane.showMessageDialog(null,"Quit the program?");
System.exit(0);
}
}
class TalkingClock
{
public void start(int interval,boolean beep)
{
ActionListener listener=new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Date now=new Date();
System.out.println("At the tone,the time is "+now);
if(beep)
Toolkit.getDefaultToolkit().beep();
}
};
Timer t=new Timer(interval,listener);
t.start();
}
}
标签:
原文地址:http://www.cnblogs.com/northsnow95/p/5548191.html