内部类

1.成员内部类

在内部类成员与外部类成员同名时,在内部类访问的是内部类成员;

在内部类如果要访问外部类,可以在内部类实例化一个外部类的对象;

内部类引用

//方法1
 Outer outer = new Outer();//先实例化外部类;
 Outer.Inter inter=outer.new Inter();
//外部类.内部类 内部对象名=外部类对象名。new 内部类();
//方法2
Outer.Inter in=new Outer().new Inter();
//外部类.内部类 内部对象名=new 外部类().new 内部类();

2.静态内部类

引用静态内部类

 StaticOuter.StaticInter si=new StaticOuter.StaticInter();
//外部类.内部类 对象名=new 外部类.内部类()//外部类引用内部类,外部类不用加括号;

3.局部内部类

只能定义在一个成员方法体中;

局部内部类,只能限制在它所在的方法体中访问;

package code62603;

public class TestLocalInterClass {
    public static void main(String[] args) {
        LocalOuter lo=new LocalOuter();
        lo.test(123);
    }
}
class LocalOuter
{
private int age=10;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    //局部内部类
    public void test(int i) //参数值被默认为final修饰 
{
//i=1000;error
class Inter
{
private int age=40;
private int num=100;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
    public void interMethod()
{
    System.out.println(age);
    System.out.println(num);
    System.out.println(i);
}
}
        Inter in = new Inter();
        in.interMethod();

    }
}

4.匿名内部类多用于接口或抽象类

一般为了重写抽象方法,可读性比较差;

package code62603;

public class TestAninymousInterClass {
    public static void main(String[] args) {
        Usb usb = new Usb(){//实际实例化是Usb接口的的实现子类,但该子类,没有具体的名成,所以被称之为匿名类
            public void service()
            {
                System.out.println("service...");
            }
        };
        System.out.println(usb.getClass().getName());//匿名类的类名code62603.TestAninymousInterClass$1
        usb.service();
    }
}
//匿名内部类
interface Usb
{
    public abstract void service();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值