1. Java 成员内部类 A是 test8的内部类
它的外部引用方法是:
外部类(test8) . 内部类(A) 变量(a1)= 外部类实例化(new test8()) . 内部类实例化(new A())
public class test8 {
class A{ //成员内部类
public A(){ //成员内部类的构造方法
System.out.println("A");
}
public void name(){ //成员内部类的方法
System.out.println("成员内部类");
}
}
public static void main(String[] args) {
/*引用方法1
test8 t=new test8();
test8.A a1=t.new A();
*/
//引用方法2
test8.A a2=new test8().new A();
//引用内部类方法
a2.name();
}
}
2. Java 局域内部类 B 是 test8的内部类
它只在于方法内或者该作用域内起作用,无法被引用它本身,只能引用包含它的方法
它的外部引用方法是:
父类(Outs) 变量(o)= 外部类实例化(new test8()) . 方法(run())
public class test8 {
public B run(){ //成员局部类(通过父类返回值)
//class B implements Out{
class B extends Outs{ //继承父类 Outs,也可以继承接口 Out
public B(){
System.out.println("B");
}
}
return new B(); //返回局域内部类 B,通过向上转换传给父类变量
}
interface Out{ //接口
}
class Outs{ //类
}
public static void main(String[] args) {
test8 t=new test8();
/*引用方法1
Outs o=t.new Outs();
o=t.run();
*/
//引用方法2
Outs o=t.run();
}
}
3. Java 匿名内部类 (相当于C) 是 test8的内部类
它的外部引用方法是:
父类(Out) 变量(o)= 外部类实例化(new test8()) . 方法(run())
public class test8 {
interface Out{ //接口
}
public Out run(){
return new Out(){//匿名内部类 (此中括号内的内容,就是匿名内部类的内容)
public void work(){
System.out.println("匿名内部类");
}
};
}
/*以上代码过程相当于如下代码
class C implements Out{
public void work(){
System.out.println("匿名内部类");
}
}
*/
public static void main(String[] args) {
test8 t=new test8();
/*引用方法1
Out o=t.new Out();
o=t.run();
*/
//引用方法2
Out o=t.run();
}
}
**3. Java 静态内部类 D 是 test8的内部类,它与外部类几乎相同。多用于程序的检测
它的外部引用方法是:
类名(D) 变量(d)= 类实例化(new D()) **
public class test8 {
static class D{ //静态内部类
public D(){
System.out.println("D");
}
public static void main(String[] args) {
System.out.println("静态内部类");
}
}
public static void main(String[] args) {
D d=new D();
D.main(args);
}
}
5. 内部类的继承
class E extends test8.A{//调用内部类,必须创建带参的构造方法
public E(test8 t){ //参数为外部类
t.super(); //调用父类方法
}
}