局部内部类:局部内部类实在方法中定义的类,所以外界是无法直接使用的,需要在方法内部创建对象并使用该类,该类可以直接访问外部类成员
示例:
package leiqiantao;
public class Outer1 {
private int num1=20;
public void method(){
int num2=10;
class Inner1{
public void show(){
System.out.println(num1+","+num2);
}
}
Inner1 i=new Inner1();
i.show();
}
}
package leiqiantao;
public class Outer1Demo {
public static void main(String[] args) {
Outer1 o=new Outer1();
o.method();
}
}
D:\Java\jdk-16.0.1\bin\java.exe -Didea.launcher.port=60353 "-Didea.launcher.bin.path=D:\IntelliJ IDEA 2018.2.8\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\dell\IdeaProjects\java学习\out\production\java学习;D:\IntelliJ IDEA 2018.2.8\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMainV2 leiqiantao.Outer1Demo
20,10
Process finished with exit code 0
匿名内部类:是局部内部类的一种。
前提:存在一个类或接口,这里的类可以是具体类也可以是抽象类
格式:
New 类名或者接口名(){
重写方法;
};
匿名内部类的本质,是一个继承了该类或者实现了该接口的子类匿名对象。
示例:package leiqiantao; public interface Show { void show(); }
package leiqiantao;
import javax.swing.*;
public class Outer2 {
private String
name="迷茫";
public
void method(){
/*
new Show(){
public void show(){
System.out.println();
}
};
new Show(){
public void show(){
System.out.println();
}
}.show();
*/
Show s=new Show(){
public void show(){
System.out.println(name);
}
};
s.show();
s.show();
}
}
package leiqiantao;
public class Outer2Demo {
public static void main(String[] args) {
Outer2 o=new Outer2();
o.method();
}
}
D:\Java\jdk-16.0.1\bin\java.exe -Didea.launcher.port=58472 "-Didea.launcher.bin.path=D:\IntelliJ IDEA 2018.2.8\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\dell\IdeaProjects\java学习\out\production\java学习;D:\IntelliJ IDEA 2018.2.8\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMainV2 leiqiantao.Outer2Demo
迷茫
迷茫
Process finished with exit code 0
匿名内部类的应用:
package leiqiantao;
public interface Climb {
void climb();
}
package leiqiantao;
public class ClimbOperator {
public void method(Climb
j){
j.climb();
}
}
package leiqiantao;
public class ClimbDemo {
public static void main(String[] args) {
ClimbOperator c=new ClimbOperator();
c.method(new Climb() {
@Override
public void climb()
{
System.out.println("猴子可以爬树");
}
});
c.method(new Climb() {
@Override
public void climb()
{
System.out.println("猪都可以上树");
}
});
}
}
D:\Java\jdk-16.0.1\bin\java.exe -Didea.launcher.port=55171 "-Didea.launcher.bin.path=D:\IntelliJ IDEA 2018.2.8\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\dell\IdeaProjects\java学习\out\production\java学习;D:\IntelliJ IDEA 2018.2.8\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMainV2 leiqiantao.ClimbDemo
猴子可以爬树
猪都可以上树
Process finished with exit code 0