一、静态内部类
public class Out {
private static String name;
private int age;
public static class In{
private int age;
public void sayHello(){
System.out.println("my name is : "+name);
//--编译报错---
//System.out.println("my age is :"+ age);
}
}
}
public static void main(String [] args){
Out.In innerClass = new Out.In();
innerClass.sayHello();
}
二、成员内部类
public class Out {
private String name;
public void showName(){
System.out.println("my name is : "+name);
}
public class In{
public void sayHello(){
System.out.println(name);
Out.this.showName();
}
}
}
public static void main(String [] args){
Out out = new Out();
Out.In in = out.new In();
in.sayHello();
}
三、方法内部类
public class Out {
private String name;
public void sayHello(){
class In{
public void showName(){
System.out.println("my name is : "+name);
}
}
In in = new In();
in.showName();
}
}
四、匿名内部类
//首先定义一个普通类
public class Out {
private String name;
private void sayHello(){
System.out.println("my name is :" + name);
}
}
//定义和使用一个匿名内部类
public static void main(String [] args){
Out out = new Out(){
@Override
public void sayHello(){
System.out.println("my name is cyy");
}
public void showName(){
System.out.println("hello single");
}
};
out.sayHello();
}
网友评论