java 内部类,
分享于 点击 8128 次 点评:207
java 内部类,
内部类的访问规则:
1.内部类可以直接访问外部类中的成员,包括私有。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式:外部类.this
2.外部类要访问内部类,必须建立内部类对象。
3.内部类在成员位置上,就可以被成员修饰符所修饰,比如private:将内部类在外部类中进行封装,static:内部类具有static的特性。
public class InnerClassDemo { public static void main(String[] args) { //访问方法一: Outer outer = new Outer(); outer.method(); //访问方法二: Outer.Inner in = new Outer().new Inner(); in.function(); } } class Outer{ private int x = 4; class Inner{ private int x = 5; void function(){ int x = 6; System.out.println("inner:"+x);//6 System.out.println("inner:"+this.x);//5 System.out.println("inner:"+Outer.this.x);//4 } } void method(){ Inner in = new Inner(); in.function(); } }
4.当内部类被静态修饰后,只能直接访问外部类中被static修饰的成员,出现了访问局限。
5.
public class InnerClassDemo { public static void main(String[] args) { new Outer.Inner().function(); } } class Outer{ private static int x = 4; static class Inner{ void function(){ System.out.println("inner:"+x); } } void method(){ Inner in = new Inner(); in.function(); } }
public class InnerClassDemo { public static void main(String[] args) { Outer.Inner.function(); } } class Outer{ private static int x = 6; static class Inner{ static void function(){ System.out.println("inner:"+x); } } void method(){ Inner in = new Inner(); in.function(); } }
6.当内部类中定义了静态成员,该内部类一定是静态的。
当外部类中的静态方法访问内部类时,内部类也必须是静态的。
相关文章
- 暂无相关文章
用户点评