Java 内部类种类及使用解析

时间:2022-07-30 22:22:14
package com.learnjava.innerclass;

class MemberInner
{
private int d = 1;
private int a = 2; // 定义一个成员内部类
public class Inner2
{
private int a = 8; public void doSomething()
{
// 直接访问外部类对象
System.out.println(d);
System.out.println(a);// 直接访问a,则访问的是内部类里的a // 如何访问到外部类里的a呢?  //InnerClass.this.*也是可以访问方法
System.out.println(MemberInner.this.a);
} } }
//

public class InnerClass {
public String a;
public void test(){
Student student = new Student();
student.goToSchool();
}
public void test1(){
//方法内部类
class ClassRoom{
public void sendMail(){
System.out.println(a);
}
}
}
public class Student{
public void goToSchool(){
System.out.println("111");
}
}
public static void main(String[] args) {
InnerClass clazz = new InnerClass();
clazz.test();
//成员内部类
Student student = clazz.new Student();
student.goToSchool();
//方法内部类

}

}