数据结构的学习历程11

内部类

实例内部类

实例内部类有额外的开销,因为实例内部类包含了两个this(一个用来调用实例内部类的属性及方法,另一个用来调用外部类的属性及方法,用法:外部类名.this.属性名或方法名).
而这个实例内部类的字节码文件为:外部类名$内部类名.class
(每个类都有自己的字节码文件)
实例内部类必须要先实例外部类对象才能实例内部类对象
实例内部类里不能有static成员变量,如果有,一定是static final修饰的

class Out{
    public int num1 = 1;
    public static int num2 = 2;
    private int num3 = 3;
    class In{
        public int num1 = 9;
        public int num4= 4;
        private int num5 = 5;
        public void func (){
            System.out.println("" + num1 +" "+num2+" "+num3+" "+num4+" "+num5);//9 2 3 4 5	
            System.out.println(this.num1);//9
            System.out.println(Out.this.num1);//1
        }
    }
}
public class Demo03 {
    public static void main(String[] args) {
        Out out = new Out();
        Out.In in = out.new In();
        in.func();
    }
}

静态内部类

静态内部类里不能访问外部类的非静态成员或方法
如果要访问,就要在静态内部类里实例化外部类的对象

class Out{
    public int num1 = 1;
    public static int num2 = 2;
    private int num3 = 3;
    static class In{
    
        Out out = new Out();//实例化外部类对象
        
        public int num2 = 9;
        public static int num4= 4;
        private int num5 = 5;
        public void func (){
            System.out.println("" + out.num1+" "+num2+" "+out.num3+" "+num4+" "+num5);
            System.out.println(Out.num2);
        }
    }
}
public class Demo03 {
    public static void main(String[] args) {
        Out.In in = new Out.In();
        in.func();
        System.out.println(Out.In.num4);
        System.out.println(in.num2);
    }
}
匿名内部类

在实例化优先级队列时用到匿名内部类,来定义这个优先级队列是大堆还是小堆
在匿名内部类里不可以捕获修改过的变量,只能捕获未修改过的变量或者常量

class Out{
    public void eat(){
        System.out.println("吃火锅!!");
    }
}
public class Demo03 {
    public static void main(String[] args) {
        Out out = new Out(){
            public void eat(){
                System.out.println("吃冰淇淋!!");
            }
        };
        out.eat();
    }
}
本地内部类(了解)
public class Demo03 {
    public static void main(String[] args) {
    	class A{
    		
    	}
    	A a = new A();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值