当前位置:网站首页>关于匿名内部类
关于匿名内部类
2022-06-13 04:59:00 【半打电话】
先来看例子
要求:在BB类中创建一个AA类对象
仔细看完这个问题,可能就会发现他十分的刁钻
首先,两个类处于不同的包下。这很正常很普通,关键是AA类中只有一个构造器,而且,他的修饰符是protected,学过java的朋友应该都知道,protected修饰符代表着不同包下不能访问调用
所有问题来了,要如何创建这个AA对象呢?
解决方案有两种:
- 就是将AA类中构造器的修饰符,修改为范围更大的public
- 就是使用今天要讲的重点
首先,来说第一种方法,这种方法可能是大多数人想到的方法,这个办法确实这直接暴力,可是,如果把AA类换乘源码呢?我们是没有办法修改源码的,所有这种办法有一定的局限性,不可取
然后,就是第二种方法了,可能刚开始看的时候是不是有点奇怪《这是啥玩意?》
换一种形式可能就清楚熟悉了
这其实就是我们的匿名内部类
那么下一个问题来了,为什么使用匿名内部类的形式就可以了呢?
首先,我们得先确定,这个
还是一个AA类么?
可以看到,它已经不是一个AA类了,那他是什么呢?
其实他是长这样的,我们应该知道匿名内部类的对象名不是我们自己取,是系统帮我们取的,所有一般来说就长得奇怪了一点
其实他是AA类的一个子类
我们可以在AA类中添加一个方法来证明
事实也如我们所证,他确实是一个AA的子类
同理,如果AA类是一个接口那么他的匿名内部类应该长这样
好了下一个问题
就是为什么匿名内部类就可以调用AA类中的protected的构造器呢?
我们可以参照这个结构想一想
既然他是一个AA类的子类,那么他应该具有什么特质呢?
首先,作为一个类 ,在没有声明构造器的情况下,系统会默认分配一个空参构造器给该对象
然后,作为一个子类,在构造器的第一行,系统也会默认调用调用父类的空参构造器!!!就是调用super()
所以,其实他长这样
因为调用了super(),所以他就理所应当的调用了父类的空参构造器,也就是AA类中被protected修饰的空参构造器
因为子类调用父类的方法属性方法构造器理所应当,所有通过这种方式,就越过了权限修饰符的限制
同理,如果我们传入了一个参数(或者多个),不过这时,系统不会分配空参构造器了,而是直接调用子类或者父类中与之匹配的构造器
边栏推荐
- Keil uses j-link to burn the code, and an error occurs: Flash download failed - one of the "Cortex-M3" solutions
- Force buckle 25 A group of K flipped linked lists
- Section 5 - Operator details
- CMB written test graphical reasoning
- C language learning log 10.4
- RMQ、LCA
- Promise processing JS multithreads get the same processing result after all the results are obtained
- C language exercise 1
- What is the saturate operation in opencv
- How to lay copper in AD (aluminum designer)
猜你喜欢
Chapter 18 pagination: Introduction
Advantages of win8.1 and win10
Configuration used by automatic teaching evaluation script
Ruoyi cloud startup tutorial (hand-held graphics)
How to implement a custom jdbc driver in only four steps?
约瑟夫问题
Sampo Lock
Section 8 - Practical commissioning techniques
Elliptic curve encryption
C language learning log 10.19
随机推荐
How to use redis
Reductive elimination
Force buckle 92 Reverse linked list II
Regular expressions in QT
Construction problem of D Xiaohong
2022 oxidation process operation certificate examination question bank and simulation examination
Sampo Lock
[try to hack] upload labs (temporarily write to 12)
【JS解决】leedcode 117. 填充每个节点的下一个右侧节点指针 II
Logical point
QT interface rendering style
RuoYi-Cloud启动教程(手把手图文)
OJ problem solution summary
rainbow
2021tami/ image processing: exploiting deep generative priority for versatile image restoration and manipulation
C language learning log 12.5
Force deduction 121 questions
Clause 30: be familiar with the failure of perfect forwarding
C language learning log 11.7
How to handle async/await error messages gracefully