内部类详解

来源:互联网 发布:无root修改手机mac地址 编辑:程序博客网 时间:2024/06/10 02:40

首先是一个内部类的实例:

class Demo{    public static void main(String[] args)    {        Outer.Inner a = new Outer().new Inner();        a.simplePrintln();        Outer1.Inner1.simplePrintln();    }}class Outer{    private int i = 1;    int j = 3;     class Inner    {        private int i =2;        int j = 4;        void simplePrintln()        {            System.out.println("print inner class");            System.out.println("print outer private i = "+ Outer.this.i);            System.out.println("print outer         j = "+ Outer.this.j);            System.out.println("print inner private i = "+ this.i);            System.out.println("print inner         j = "+ this.j);        }    }}class Outer1{    private static int i = 1;    static int j = 3;    static class Inner1    {        private static int i =2;        static int j = 4;        static void simplePrintln()        {            System.out.println("print inner1 class");            System.out.println("print outer1 private i = "+ i);            System.out.println("print outer1         j = "+ j);            System.out.println("print inner1 private i = "+ i);            System.out.println("print inner1         j = "+ j);        }    }}

内部类访问规则:
1. 内部类可以直接访问外部类的成员,包括private 成员。方法是为: 外部类名.this
2. 外部类要访问内部类必须要建立内部类对象,若外部其他类想要访问内部类的并使用其中方法必须采用以下格式:
外部类名.内部类名 = 外部对象.内部对象;
Outer.Inner a = new Outer().new Inner();
3.当内部类在成员位置上,就可以被内部成员修饰符修饰,
比如: private, 封装内部类
static, 内部类静态的化,但要注意的是当内部类被静态化后,只能访问外部类中的static成员变量,即出现访问局限;
在外部其他类中,如何访问内部静态类呢?
Outer.Inner.function();

注意:
当内部类中定义了static 成员,该内部类必须为static;
当外部类中的静态方法访问内部类时,该类必须为静态

当描述某对象时,若该对象内部还有对象,该类用内部类描述,
例如:对象电脑内部有硬盘(对象化),内存(对象化),显卡(对象化)

class Computer{    private class Memory    {    }    private class harddrive    {    }    private class Gpu    {    }}
class Outer2{    int x = 3;    void method()    {        class Inner2 //该处的class不能被static修饰,因为static只能修饰成员变量,而class Inner在局部变量        {            void function()            {                System.out.println(Outer2.this.x);            }        }    }}
0 0