频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

Java中的内部类问题

来源:qqread.com 作者:佚名 出处:巧巧读书 2008-07-25 进入讨论组
下一页 1 2 3 

.关于内部类的说明
    1)在一个类中定义另外一个类,这个类就叫做内部类(inner class) 。内部类的定义和普通类的定义没什么区别,它可以直接访问和引用它的外部类的所有变量和方法(包括private),就像外部类中的其他非static成员的功能一样。

区别是,外部类只能声明为public和default,而内部类可以声明为private和protected。 

    2)当我们建立一个inner class时,其对象就拥有了与外部类对象之间的一种关系,这是通过一个特殊的this reference形成的,当内部类的成员方法中访问某个变量/方法时,如果在该方法和内部类中都没有定义过这个变量,调用就会被传递给内部类中保存的那个外部类对象的引用(OuterClass.this),通过那个外部类对象的引用去调用这个变量。

    2.内部类变量访问
    2.1在main中直接从外部类调用内部类的方法
    package org.zj.sample;
    class Outer {
        private int index = 100;
        class Inner {
             private int index = 50;
             void print() {
               int index = 30;
               System.out.println(index); // 30
               System.out.println(this.index); // 50
               System.out.println(Outer.this.index); // 100
             }
    }

        void print() {
             Inner inner = new Inner();//得到内部类的引用
             inner.print();
        }
    }

    class Test {
        public static void main(String[] args) {
             Outer outer = new Outer();
             outer.print();
        }
    }

    该示例程序列出了重名成员变量分布的3种情况。
    访问内部类方法中的变量:
    System.out.println(index);

    访问内部类中的成员变量:
    System.out.println(this.index);

    访问所在外部类的成员变量:
    System.out.println(Outer.this.index);


    2.2在main中显式返回内部类引用
    package org.zj.example;
    class Outer {
        private int index = 100; 
        class Inner {
             private int index = 50;
             void print() {
               int index = 30;
               System.out.println(index); // 30
               System.out.println(this.index); // 50
               System.out.println(Outer.this.index); // 100
             }
    }

        Inner getInner() {
             return new Inner();//返回一个内部类的引用
        }
    }

    class Test {
        public static void main(String[] args) {
             Outer outer = new Outer();
             Outer.Inner inner = outer.getInner();
             inner.print();
        }
    }


    2.3当main方法在Outer类内部
    package org.zj.sample1;
    class Outer {
        private int index = 100;
        class Inner {
             private int index = 50;
             void print() {
               int index = 30;
               System.out.println(index); // 30
               System.out.println(this.index); // 50
               System.out.println(Outer.this.index); // 100
             }
        }

        Inner getInner() {
             return new Inner();
        }

        public static void main(String[] args) {

更多文章 更多内容请看Java环境安装配置Java编程开发手册Java的类专题,或进入讨论组讨论。
下一页 1 2 3 
收藏此文】【 】【打印】【关闭
较早的文章:JAVA反编译工具总结

较新的文章:Java中的流程控制
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
讨论组问题推荐
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章