JavaSE -- 内部类

为什么需要内部类

  • 内部类提供了某种进入外围类的窗口,解决“多重继承”的问题

  • 每个内部类都能够独立地继承字一个接口的实现,所以无论外围类是否已经继承了某个接口的实现,对于内部类都是没有影响的

    interface A {}
    interface B {}
    
    calss X implements A,B {}
    
    calss Y implements A {
    B makeB() { return new B() {}; }
    }

使用.this.new

  • 如果需要生成对外部类对象的引用,可以使用内部类的名字后面紧跟.this

    public class DotThis{
    void f(){System.out.println("DotThis.f()");}
    
    public class Inner{
        public DotThis outer() {
            // return DotThis class
            return DotThis.this;
        }
    }
    
    public Inner inner() {
        return new Inner(); 
    }
    
    public static void main(String[] args){
        DotThis dt = new DotThis();
        DotThis.inner dti = dt.inner();
        dti.out.f();
    }
    }
    
    /* out
    DotThis.f()
    */
    
  • 创建某个内部类对象 必须先创建外部类,再使用.new来创建内部类

    public class DotNew {
    public class Inner {}
    public static void main(String[] args) {
      DotNew dn = new DotNew();
      DotNew.Inner dni = dn.new Inner();
    }
    }

匿名内部类

  • 创建一个继承自基类的匿名类的对象(匿名内部类末尾;

    //无参
    public class Parcel7 {
    //contents() 方法将返回值的生成与表示这个返回值的类的定义结合在一起
    public Contents contents () {
      return new Contents () {
        privatte int i=11;
        public int value () {return i;}
      };
    }
    
    public static void main (String[] args) {
      Parcel7 p = new Parcel7();
      Contents c = p.contents();
    }
    }
    
    //含参
    public class Parcel8 {
    public Wrapping wrapping (int x){
        return new Wrapping(x) {
            public int value() {
                return super.value() *47;
            }
        };
    }
    
    public static void mian(Stringp[] args) {
        Parcel8 p =new Parcel8();
        Wrapping w = p.wrapping(10);
    }
    }
  • 实例初始化实现内部类的构造器(变量必须是fianl

    public class Parcell0 {
    public Destination 
    destination (final String dest, final float price) {
        return new Destination() {
            private int cost;
            {
                cost = Math.round(price);
                if(cost >100)
                    System.out.println("over budget!");
            }
            private String label = dest;
            public String readLabel() {return label;}
        };
    }
    }

内部类的继承

calss WithInner {
    calss Inner {}
}

public calss InheritInner extends WithInner.Inner {
    //! InheritInner() //Won't complie
    InheritInner (WithInner wi) {wi.super();}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值