静态内部类
非静态内部类成员内部类
方法内部类
匿名内部类
package study;
/**
* 测试内部类
*
* @author http://blog.csdn.net/thewaiting
*
*/
public class Text {
// 内部类 static 前面可以加修饰符
private static class StaticClass {
}
// 普通内部类
private class FieldClass {
}
void sayHellow() {
// 方法内部类 局部内部类
class LocalClass {
}
// 匿名内部类
Runnable runnable = new Runnable() {// 定义了匿名内部类的类体 创建了匿名内部类的一个实例
@Override
public void run() {
}
};
}
}
静态内部类的基本用法:
静态内部类可以包含静态成员,非静态成员
静态内部类可以直接调用外部的类的静态属性,静态方法。但不能调用外部类的普通属性和普通方法
在不相关的类中,可以直接创建静态内部类的对象(不需要通过所在外部类)
静态内部类实际上和外部类联系很少,也就是命名空间上的联系
package study;
import study.Text3.StaticClass2;
/**
* 测试静态内部类的详细用法
* @author http://blog.csdn.net/thewaiting
*
*/
public class Text2 {
public static void main(String[] args) {
//创建内部类的实例
Text3.StaticClass2 a = new Text3.StaticClass2();
StaticClass2 b = new StaticClass2();//import study.Text3.StaticClass2;
}
}
class Text3{
int c = 3;
static int d =5;
//定义内部类
void ttt(){
StaticClass2 class2 =new StaticClass2();
}
public static class StaticClass2{
int a = 3;
static int b =5;
public void text() {
//静态内容
System.out.println(d);
//静态内部类中只能调用静态成员
}
}
}
package study;
import study.Text3.Text;
/**
*
* @author http://blog.csdn.net/thewaiting
*
*/
public class Text2 {
public static void main(String[] args) {
//创建成员内部类
Text3 text3 = new Text3();
Text t = text3.new Text();//import study.Text3.Text; 依赖外部类
t.text1();
}
}
class Text3{
private int a = 3;
int b = 10;
public void ttt() {
//创建内部类
Text text = new Text();
}
//成员内部类
class Text{//方便的使用外部类的成员
//成员内部类不能有静态的成员和方法 除非初始化final类型
final static int f = 3;
void text1(){
//可以使用外部类的成员
System.out.println(a);
System.out.println("内部类对象"+this);//内部类对象 先有外部类的对象 再有内部类对象
System.out.println("外部类对象"+Text3.this);//外部类对象
}
}
}
方法内部类
package study;
/**
* 测试方法内部类(也叫局部内部类)
* @author http://blog.csdn.net/thewaiting
*
*/
public class Text {
public static void main(String[] args) {
}
}
class Out{
public void test(){
int a = 3;
//不能用修饰符
//只在这个方法里可见
class Inner{
//属性 不能定义静态属性
int b = 4;
//定义方法
void tt(){
//不能使用方法的属性 int a = 3;除非是final属性
//方法的生命周期和方法内部类对象的生命周期
}
}
//方法内部使用
Inner inner = new Inner();
}
}