内部类

来源:互联网 发布:全国驾校数据 编辑:程序博客网 时间:2024/06/05 04:17

1.内部类的声明定义引用

class Outer {

private static String str="hello";
 class Inner{
public void printInfo(){
System.out.println("你好"+str);
}
}

}
public class TestDemo{
public static void main(String args[]){
//引用格式 
//外部类.内部类 内部类对象=new 外部类().new 内部类()
Outer.Inner in=new Outer().new Inner();
in.printInfo();
}

}

2.static 定义的内部类

class Outer {
private static String str="hello";
 static class Inner{
public void printInfo(){
System.out.println("你好"+str);
}
}
}
public class TestDemo{
public static void main(String args[]){
//引用格式 
//外部类.内部类 内部类对象=new 外部类.内部类()
Outer.Inner in=new Outer.Inner();
in.printInfo();
}
}


3.定义在方法内

class Outer {
private  String str="hello";
public void fun(int num){//jdk 1.8之后才可以,1.7 版本及以前版本会报错
class Inner{
public void print(){
System.out.println(num);
System.out.println(str);
}
}
new Inner().print();
}

}
public class TestDemo{
public static void main(String args[]){
new Outer().fun(100);
}
}


4 .总结

(1)破坏程序的结构

(2)方便进行私有属性的访问

(3)如果发现类名称上出现了“.”应该想到是内部类的概念


原创粉丝点击