java中 什么是内部类

发布时间:2017-03-16 14:06

java内部类

内部类学习

所谓内部类(Inner Class),顾名思义,就是指定义在另外一个类中的类,我们为什么要这么做呢?为什么不直接定义它而要在别的类中定义一个内部类呢?这样做主要有如下三个原因:

1. 内部类的方法可以访问它所在的外部类中的所有域,包括私有型别的;

2. 对于同一个包中的其它类它是隐藏的;

3. 匿名的内部类可以让我们很方便的定义事件响应(call back),这在GUI编程中很常见;

一.内部类(inner class)如何访问外部类(outer class)中的域

因为安全机制的原因,内部类通常声明为private类别,因此,只有在内部类所在的外部中才能够创建内部类的对象,对其它类而言它是隐藏的。另外,只有内部类才会用到private修饰符,一般的类如果用private修饰符则会报错。

下面看如下的代码:

Java代码

package cn.edu.hust.cm.test;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.awt.Toolkit;

import javax.swing.JOptionPane;

import javax.swing.Timer;

public class InnerClassTest {

public InnerClassTest() {

super();

// TODO Auto-generated constructor stub

}

public static void main(String[] args) {

Court court=new Court(10000,true);

court.start();

JOptionPane.showMessageDialog(null,"停止么,CMTobby?");

System.exit(0);

}

}

class Court{

public Court(int interval,boolean beep){

this.interval=interval;

this.beep=beep;

}

public void start(){

TimerPrinter action=new TimerPrinter();

Timer t=new Timer(interval,action);

t.start();

}

private int interval;

private boolean beep;

private class TimerPrinter implements ActionListener{

public void actionPerformed(ActionEvent e){

System.out.println("Cindyelf,would you be my mm?");

if(beep) Toolkit.getDefaultToolkit().beep();

}

}

}

java中 什么是内部类的评论条评论