[JavaSE] Instructions for using inner classes

In java, we often use inner classes. We wrote demos before and sent them out today in case we need them in the future.


package com.huat.InnerClass;


/*
*@author: 
*@see功能介绍:内部类
*@vesion版本号:JDK1.8
*2018年1月13日
*
*
*内部类的作用:
*   1.提供更好的封装,只能让外部类直接访问,
*不允许同一个包中的其他类直接访问
*   2.内部类可以直接访问外部类的私有属性,
*内部类会被当作外部类的成员,但是外部类不能访问内部类的内部属性
*
*使用场合:内部类职位外部类提供服务的情况下使用
*   
*成员内部类
*   1.非静态内部类:
*           必须寄存在外部类中,非静态的内部类对象单独属于外部类某个对象
*   2.静态内部类:不需要先定义外部类
*匿名内部类
*局部内部类:
*   定义在方法中
*/
public class OutterClass {

    public static void main(String[] args) {
        Face f = new Face();
        Face.Nose n = f.new Nose();
        n.breath();

        Face.Ear e = new Face.Ear();
        e.listen();
    }

}

class Face {
    private int type = 100;
    static String color = "fffff";

    class Nose {
        String type = "瓜子脸";

        public void breath() {
//          通过外部类.this.属性访问外部属性
            System.out.println("type " + Face.this.type);
            System.out.println("呼吸...");
            System.out.println(color);
        }
    }
    /**
     * 静态内部类看作外部类的一个静态成员
     * 
     */
    static class Ear {
        public void listen() {

//          System.out.println("type" + type); //静态内部类不能访问外部普通属性
            System.out.println("color " + color);
        }
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325863706&siteId=291194637