java学习之内部类

内部类的访问规则:

1.内部类可以直接访问外部类中的成员,包括私有

   之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式:  外部类名.this

2.外部类要访问内部类,必须要建立内部类对象

 

访问格式:

1.当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中,可以直接建立内部类对象。

格式:外部类名.内部类名  变量名 = 外部类对象.内部类对象

Outer.Inner in=new Outer().new Inner();

2.当内部类在成员位置上,就可以被成员修饰符所修饰。

   比如,private:将内部类在外部类中进行封装

              static:内部类就具有static的特性(当内部类被static修饰后,只能直接访问外部类中的static成员,出现了访问局限。

package com.dreamy.day03;

/**
 * @author dreamy
 *
 */
class Outer{
    private static int x=3;
    
    static class Inner{//静态内部类
        static 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 in=new Outer().new Inner();
//        in.function();
        Outer.Inner.function();
    }
}

 

              在外部其他类中,如何直接访问static内部类的非静态成员呢?

new Outer.Inner().function();

               在外部其它类中,如何直接访问static内部类的静态成员呢?

Outer.Inner.function();

注意:当内部类中定义了静态成员,该内部类必须是static的。

           当外部类中的静态方法访问内部类时内部类也必须是静态的

package com.dreamy.day03;

/**
 * @author dreamy
 *
 */
class Outer{
    private static int x=3;
    
    static class Inner{//静态内部类
        static void function() {
            System.out.println("inner:"+x);
        }
    }
    static class Inner2{
        void show() {
            System.out.println("inner2.show");
        }
    }
    public static void method() {
//        Inner.function();
        new Inner2().show();
    }
}
public class InnerClassDemo {
    public static void main(String[] args) {
    }
}

 

 

注意:直接访问内部类中的成员,如下图:

package com.dreamy.day03;

/**
 * @author dreamy
 *
 */
class Outer{
    private int x=3;
    
    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 in=new Outer().new Inner();
        in.function();
    }
}

 

内部类的使用:当描述事物时,事物的内部还有事物,该事物用内部类来描述。因为内部事务在使用外部事物的内容。//一般用于程序设计上,把内部类私有化,提供一个公有方法来访问

class Body{
     
     private class XinZang{
     
     }
     public void show(){
new XinZang().
} }

 

posted @ 2017-12-14 21:33  dreamy_java  阅读(123)  评论(0编辑  收藏  举报