内部类
- 内部类可以在类体中,或方法中声明。
- 内部类中不可以声明static的变量或者方法。
- 内部类的方法可以调用外部类的方法。
public class Outer {//定义一个外嵌类
private int index = 100;
int x = 10;
class inner{//定义一个内部类
private int index = 50;
public void print() {//定义内部类的方法
int index = 30;
System.out.println(index);//调用局部变量 30
System.out.println(this.index);//调用内部类的变量 50
System.out.println(Outer.this.index);//调用外部类的变量 100
}
}
}
//测试类 mian 方法
public class TestSpeak {
public static void main(String[] args) {
Outer outer = new Outer();//创建外部类对象
Outer.inner in = outer.new inner();//使用外部类对象创建内部类对象
in.print();
}
}
输出结果:
30
50
100
:内部类可体现封装性,隐藏相关信息;
:内部类可以实现多重继承,实现复杂的数据结构。
:等。。
匿名类
- 匿名类:将类体与创建对象联合在一起,为了简化代码。
- 匿名类一定是内部类,不许有static方法。
abstract class Hello { // 抽象类
abstract void sayHello();
}
//用匿名类做方法的参数
class TestNoNameInner1 {
public static void main(String[] args) {
new TestNoNameInner().callInner(
/
new Hello() { // 用匿名类,做方法的参数
public void sayHello() {
System.out.println("Hello!哈哈");
}
}
/
);
}
//用抽象类做参数(Hello e), 可用上诉匿名类方法创建对象。
public void callInner(Hello a) {
a.sayHello();
}
}