黑马程序员技术交流社区
标题: 内部类的访问规则和格式 [打印本页]
作者: 画了一个圈儿 时间: 2014-8-20 12:27
标题: 内部类的访问规则和格式
- class Outer
- {
- private static int x = 1;
- static class Inner
- {
- int x = 3;
- public void method()
- {
- int x = 5;
- System.out.println("x="+x); //x=5
- System.out.println("x="+this.x); //x=3
- System.out.println("x="+Outer.this.x); //x=1
- }
- }
- public void function()
- {
- Inner in = new Inner();
- in.method();
- }
- }
- class InnerClassDemo
- {
- public static void main(String[] args)
- {
- Outer ou = new Outer(); //通过外部类成员访问内部类;
- ou.function();
- }
- }
复制代码内部类的访问规则:
1、内部类可以直接访问外部类中的成员,包括私有成员。因为内部类中持有了一个外部类的引用,格式:外部类名
.this。
- class Outer
- {
- int x = 1;
- class Inner
- {
- public void method()
- {
- System.out.println("x="+x); //x=1; 这里的x相当于Outer.this.x
- }
- }
- }
复制代码 2、外部类要访问内部类,必须建立内部类对象:
Outer.Innerin = new Outer().new Inner();
in.method();
内部类的访问格式:
1、当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中直接建立内部类对象。
格式: 外部类名.内部类名 变量名 = 外部类对象.内部类对象;
Outer.Innerin = new Outer().new Inner();
2、当内部类定义在成员位置上,就可以被成员修饰符所修饰。比如:
private:将内部类在外部类中进行封装
static:内部类具备了静态特性。
当内部类被static修饰后,只能直接访问外部类中的static成员,即出现了访问局限。
在外部其他类中,如何直接访问static内部类中的非static成员呢?
new Outer.Inner().method();
在外部其他类中,如何直接访问static内部类中的static成员呢?
Outer.Inner.method(); // method()被static修饰时
注意:当内部类中定义了静态成员,该内部类必须是static修饰的。
当外部类中的静态方法访问内部类时,内部类也必须是static的。
什么时候定义内部类:
当描述事物时,事物的内部还有事物,该事物用内部类来描述。因为内部事物在使用外部事物的内容。比如body和heart的关系,为body定义一个类,那么heart类应该定义在body类内部,并封装,只有满足一定条件时才能在外部其他类中访问heart类的成员和方法。
作者: chengzhx76 时间: 2014-8-20 15:48
借阅。。。
作者: nadax 时间: 2014-8-20 17:07
刚好看到这。。。 感觉开发中用的不多 但是最起码要看懂
作者: 画了一个圈儿 时间: 2014-8-20 17:29
呵呵 后面还有用到的地方,所以整理整理复习一次
作者: nadax 时间: 2014-8-20 17:44
谢谢楼主,看着正有点晕,你这个规则看完 整个人都好了
作者: nadax 时间: 2014-8-20 17:45
怎么没有匿名内部类的,这有点晕啊。嘿嘿 有点过分 见谅
作者: 画了一个圈儿 时间: 2014-8-20 18:02
匿名内部类又发了一个帖子,格式不好调整,所以分开发的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |