内部类(访问规则和静态内部类)

来源:互联网 发布:max809焊盘数据图片 编辑:程序博客网 时间:2024/05/29 13:52
/* 内部类的访问规则: 1、内部类可以直接访问外部类的成员,包括私有。    之所以可以直接访问外部类中的成员,是因为内部类中持有了外部类中的一个引用 格式:外部类名.this 2、外部类要访问内部类必须要建立内部类对象。     访问格式:1、 当内部类定义在外部类的成员位置上,而且非私有,可以在外部类其他类中直接建立内部类对象。  格式:     外部类名.内部类名 变量名 = 外部类对象.内部类对象  outer.inner in=new outer().new inner();  2、当内部类在成员位置上,就可以被成员修饰符所修饰     比如 private:将内部类在外部类中进行封装。     static:内部类就具备static特性。     当内部类被static修饰后,只能直接访问外部类中的静态成员,出现了访问局限。  在外部其他类中如何访问静态内部类 格式:      new 外部类名.内部类名.内部类成员      访问静态成员:                                        外部类名.内部类名.内部类成员 当内部类中定义了静态成员,该内部类必须是静态的。                                       */class outer{private int x=3;//内部类class inner{int x=4;void function(){int x=5;//直接写x打印的是5,加上this打印的是4,再加上outer打印的3System.out.println("inner:"+outer.this.x);}}void method(){inner in=new inner();in.function();}}public class InnerclassDemo {public static void main(String[] args) {outer out=new outer();out.method();//直接访问内部类成员,固定格式outer.inner in=new outer().new inner();in.function();}}

5 0
原创粉丝点击