嵌套类可分为两种不同的类型:使用static修饰的嵌套类称为静态嵌套类;而非static得嵌套类被称为内部类。
其中内部类又可细分为三种形式:
1)普通的内部类
2)局部内部类
3)匿名内部类:也称为匿名类,定义在方法或语句块中,该类没有名字、只能在其所在之处使用一次。
内部类使用举例:
class A {
private int s;
public class B{
public void mb() {
s = 100;
System.out.println("在内部类B中s=" + s);
}
}
public void ma() {
B i = new B();
i.mb();
}
}
public class TestInner {
public static void main(String args[]){
A o = new A();
o.ma();
}
}
匿名类使用举例:
public interface Swimmer{
public abstract void swim();
}
class TestAnonymous2{
public static void main(String args[]){
TestAnonymous2 ta = new TestAnonymous2();
ta.test(new Swimmer(){
public void swim(){
System.out.println("I'swimming!");
}
});
}
public void test(Swimmer swimmer){
swimmer.swim();
}
}
|