匿名类部类

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();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值