1.内部类的分类
- 成员内部类
- 局部内部类(包含匿名内部类)
2.成员内部类:定义在成员方法外部
- 定义格式
修饰符 class 外部类名称 {
修饰符 class 内部类名称 {
//.....
}
//.....
}
public class body {
public class heart{
public void method1(){
System.out.println("内部类的方法");
}
}
public void method2(){
System.out.println("外部类的方法");
}
}
内部类调用外部类的成员变量和方法时,随意用
外部类调用内部类的成员变量和方法时,需要内部类对象
public class body {
public class heart {
public void method1() {
System.out.println(name); 内部类调用外部类的成员变量,随意用
method2(); 内部类调用外部类的成员方法,随意用
}
}
String name = "张丹";
public void method2() {
System.out.println("外部类的方法");
}
public void method3(){
heart H = new heart(); 外部类调用内部类的成员变量和方法时,需要内部类对象
H.method1();
}
}
- 使用
- 间接方式:在外部类的方法中,使用内部类,然后main中调用外部类的方法
在外部类的方法中,使用内部类:
public class body {
public class heart {
public void method1() {
System.out.println("内部类的方法");
}
}
public void method2() { 在外部类的方法中,使用内部类:
heart H = new heart();
H.method1();
}
}
然后main中调用外部类的方法
public class Demo1 {
public static void main(String[] args) {
body b = new body();
b.method2(); 然后main中调用外部类的方法
}
}
2. 直接方式:
外部类名称.内部类名称 对象名 = new 外部类名称().new 内部类名称();
public class body {
public class heart {
public void method1() {
System.out.println("内部类的方法");
}
}
}
public class Demo1 {
public static void main(String[] args) {
body.heart h = new body().new heart();
h.method1();
}
}
- 内部类重名
public class Outer {
int num = 10 ;
public class Inter{
int num =20;
public void method(){
int num = 30;
System.out.println(num); 10
System.out.println(this.num); 20
System.out.println(Outer.this.num); 30
}
}
}
3.局部内部类:定义在成员方法内部
- 定义格式
public class Outer02 {
public void method(){
class Inter{
//...
}
}
}
- 使用:只能间接使用,在外部类的方法中,使用内部类,再mian外部方法调用
public class Outer02 {
public void method() {
class Inter {
public void methodInner() {
System.out.println("局部内部类的方法");
}
}
Inter in = new Inter(); 在外部类的方法中,使用内部类
in.methodInner();
}
}
public class Demo02 {
public static void main(String[] args) {
Outer02 obj = new Outer02();
obj.method();
}
}
4.局部内部类中的匿名内部类
如果接口的实现类(或者父类的子类)只需要使用一次
那么,可以省略实现类(子类),而改用匿名内部类
- 定义格式
接口名称 对象名 = new 接口名称(){
覆盖重写接口所有抽象方法;
};
接口:
public interface Interface {
public abstract void method();
}
匿名内部类:
public class Demo03 {
public static void main(String[] args) {
Interface obj = new Interface() {
@Override
public void method() {
}
};
}
}