内部类分为:
非静态内部类
package 内部类;
//脸类
public class 非静态Face {
//外部类成员
private String shape = "国字脸";
//
private void run() {
System.out.println("脸上外部类方法");
}
//鼻子内部类
class Nose{
private void run() {
System.out.println("鼻子内部方法");
}
public void breath() {
System.out.println("呼吸呼吸");
//属于某个外部类的对象
System.out.println("鼻子长脸上了"+非静态Face.this.shape+"形状的脸上");
//两个方法相同会默认访问内部类的方法
run();
//重名时 :外部类名+this+加外部方法 Face.this.run();
}
}
//耳朵内部类
class Ear{
public void tingHua() {
System.out.println("耳朵听话");
//访问外部脸类成员
System.out.println("耳朵长再脸上"+非静态Face.this.shape+"形状的脸上");
}
}
public static void main(String[] args) {
//创建鼻子类对象并且访问自己成员方法和外部类的成员
非静态Face.Nose nose = new 非静态Face().new Nose();
nose.breath();
非静态Face.Ear ear = new 非静态Face().new Ear();
ear.tingHua();
}
}
静态内部类:
静态内部类中不能访问外部类的普通属性也就是只能访问静态成员
匿名内部类
package 内部类;
public class 匿名Test {
public void test(A a) {
a.run();
}
public static void main(String[] args) {
匿名Test test1 = new 匿名Test();
/* test1.test(new AA()); */
test1.test(new A(){
public void run() {
System.out.println("匿名内部类");
}
});
}
}
/*
* //有名字内部类 class AA implements A { public void run() {
* System.out.println("有名内部类");
*
* } }
*/
interface A {
void run();
}
局部内部类
循序渐进