public static void main(String[] args) {
A.B.Method();//静态方法直接访问
new A.B().Method2();//创建内嵌类的对象访问其实例方法
}
}
二.方法中包含类(内嵌类和匿名内嵌类)
1.内嵌类
/**
* 运行结果是:
* y = 5
n = 5
x = 3
* 方法内定义的内嵌类只能访问方法内定义的带finnal修饰的变量
*
*/
public class A{
private int x = 3;
public void Method(int m){
final int n = x+2;
class B{ 方法中的内嵌类
private int y = 5;
public void Method2(){
System.out.println("y = "+y);
System.out.println("n = "+n);
//System.out.println("m = "+m);//访问m不允许
System.out.println("x = " +x);
}
}
B b = new B();//在方法内创建内嵌类的对象
b.Method2();//调用内嵌类的方法
}
public static void main(String[] args) {
A a = new A();
a.Method(6);
}
}
2.匿名内嵌类
/**
* new sample(){//由接口派生匿名内嵌类
public void method(){
System.out.println("just test!!");
}
}.method();//调用内嵌类定义的方法
* 创建一个匿名内嵌类实现sample接口,同时创建该匿名类的一个对象
*
*/
interface sample{
void method();
}
public class A{
void testMethod(){
new sample(){//由接口派生匿名内嵌类
public void method(){
System.out.println("just test!!");
}
}.method();//调用内嵌类定义的方法
}
public static void main(String arg[]){
A a = new A();
a.testMethod();
}
}
匿名类部类
最新推荐文章于 2022-08-13 18:17:57 发布