java基础——内部类

面试题1:

请填空分别输出10、20、30

class Outer {
	public int num = 10;
	class Inner{
		public int num = 20;
		public void show() {
			int sum = 30;
			System.out.println(?);
			System.out.println(?);
			System.out.println(?);
		}
	}
}

答案:

num;//30

this.num;//20

Outer.this.num;//10

class Outer {
	public int num = 10;//Outer.this.num
	class Inner{
		public int num = 20;//this.num
		public void show() {
			int sum = 30;//num
			System.out.println(num);//30
			System.out.println(this.num);//20
			System.out.println(Outer.this.num);//10
		}
	}
}
public class test{
    public static void main(String[] args){
        Outer.Inner oi = new Outer().new Inner();//如果Inner是静态类,则new Outer.Inner()
        oi.show();     
    } 
}

注意:

1.内部类和外部类没有继承关系;

2.通过外部类名限定this对象

Outer.this

面试题2:

局部内部类访问局部变量的注意事项:

A.局部内部类访问局部变量必须用final修饰

B.为什么?

        因为局部变量是随着方法的调用而调用,随着调用完毕而消失。而堆内存的内容并不会立即消失,所以加入final修饰后,这个变量就变成了常量。(既然是常量了,假设常量的数据是20,那么即使这个局部变量消失了,但它在内存中存储的是20,所以我还是有数据在使用)

例子:

class Outer {
	public void method() {
		final int num = 20;//final修饰
		class Inner{//局部内部类		
			public void show() {
				System.out.println(num);
			}
	}
		Inner i = new Inner();
		i.show();
	}
}
public class test{	
    public static void main(String[] args){
        Outer o = new Outer();
        o.method();     
    } 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值