corejDay1
1、内部类:
有什么用?
1、可以访问该类定义所在作用域中的数据,包括私有数据。
2、当想定义一个回调函数而不想编写大量代码时,使用匿名内部类比较便捷。
3、内部类可以对同一个包中的其他类隐藏起来。
什么时候用?
1、想省代码
2、想访问本类数据
3、想隐藏数据(要写的类,仅被一个类使用一次)
简单内部类举例
:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; /**
* Created by xkfx on 2017/2/12.
*/
public class InnerClassTest{
public static void main(String[] args){
TalkingClock clock = new TalkingClock(1000 , true); //参数改成100系统不响铃
clock.start(); JOptionPane.showMessageDialog(null , "Quit?"); //没有这两行代码,程序无法运行???
System.exit(0);
}
} class TalkingClock{
private int interval;
private boolean beep; public TalkingClock(int interval, boolean beep){
this.interval = interval;
this.beep = beep;
} /**
* Starts the clock
*/
public void start(){
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval , listener);
t.start();
} private class TimePrinter implements ActionListener{ //设置成private就实现了封装 //这里有一个不可见的隐式引用 outer = 外围类对象
//下面的beep等价于 outer.beep
//TimePrinter有一个隐式的构造器 public TimePrinter(TalkingClock clock){ outer = clock; } @Override
public void actionPerformed(ActionEvent e) {
System.out.println("...");
if(beep) Toolkit.getDefaultToolkit().beep(); //内部类可以访问外围类对象的数据域
}
}
}
内部类的语法规则
:
局部内部类
:在一个方法中定义类
匿名内部类
:例如
public void start(int interval, boolean beep)
{
ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent event){
System.out.println("...");
if(beep){
Toolkit.getDefaultToolkit().beep();
}
}
};
Timer t = new Timer(interval, listener);
t.start();
}
如何将静态内部类镶嵌在辅助类中
:
2、代理
有什么用?
可以在运行时创建一个实现了一组给定接口的新类。
只有在编译时无法确定需要实现哪个接口时才有必要使用。
什么时候用?
corejDay1的更多相关文章
随机推荐
- New text file line delimiter
Window -> Preferences -> General -> Workspace : Text file encoding :Default : 选择此项将设定文件为系统默 ...
- ELK之filebeat-redis-logstash-es构架模式
下载filebeat的rpm包安装filebeat wget https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.3.0- ...
- linux:使用apt、dpkg工具安装软件
先总结一下安装软件常用命令: % apt sudo apt install xxxx sudo apt list xxxx % dpkg安装deb文件 sudo dpkg -i xxxx.deb 学习 ...
- PLSQL Package包的使用
创建包头 create or replace package pak_kingsql is procedure pro_kingsql(p_one in varchar2,p_two out varc ...
- centos7 安装ftp
安装VSFTPD 1.首先确认系统内无VSFTPD. rpm -qa|grep vsftpd 若有的话会显示vsftpd-x.x.x.-x.xxx.x86_64 若没有的话会空返回 2.安装VSFTP ...
- grunt学习三-bower(一)
bower是什么?官网给出的 a package manager fow the web.简单说引入文件版本管理,例如jquery,传统做法到jquery的官网下载下,在引入,这样比较繁琐,也不利用 ...
- javaScript高级教程(五) Event Flow
1.两个阶段三个模型:Netscape支持事件捕获,IE支持事件冒泡,w3c是先捕获后冒泡 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 S ...
- python中执行shell命令行read结果
+++++++++++++++++++++++++++++ python执行shell命令1 os.system 可以返回运行shell命令状态,同时会在终端输出运行结果 例如 ipython中运行如 ...
- ie8兼容半透明效果css
1.opacity:0.5;(半透明效果在ie9及以上版本适用,ie8及以下不兼容) 解决办法:在css中加入filter: progid:DXImageTransform.Microsoft.Alp ...
- 十天精通CSS3(5)
background-origin 设置元素背景图片的原始起始位置. 语法: background-origin : border-box | padding-box | content-box; 参 ...