内部类

定义个一个内部类

package com.encapsulation.Demo07;

public class Outer {

    private int id;

    private static int statId;

    public Outer(int id) {
        this.id = id;
        statId = id;
    }
    
 	// 方法重载
    public Outer(String name) {
        System.out.println(name);
    }

   
    public void out() {
        System.out.println("这是外部类的方法");
    }

    public void getId() {
        System.out.println(id);
    }

    // 内部类
    public class Inner {
        public void in() {
            System.out.println("这是内部类的方法");
        }

        public void getId() {
            System.out.println(id);
        }
    }

    // 静态内部类  只能获取静态属性 无法实例化
    public static class statInner {
        public void getId() {
            System.out.println(statId);
        }
    }

}

使用内部类

package com.encapsulation.Demo07;

public class App {
    public static void main(String[] args) {
        Outer outer = new Outer(100);
        Outer.Inner inner = outer.new Inner();

        // 静态内部类无法实例化
       // Outer.statInner statInner = outer.new statInner();

        // 可以通过 内部类获取私有属性
        inner.getId();
        outer.getId();
        

        // 匿名内部类,不用将实例保存到变量中
        new Apple().eat();

        // 接口的类实现 高阶写法
       UserService userService = new UserService(){
            @Override
            public void hello(String name) {
                System.out.println(name);
            }
        };
        userService.hello("江");
    }
}

class Apple {
    public void eat() {
        System.out.println("1");
    }
}

interface UserService {
    void hello(String name);
}
posted @ 2021-06-29 14:11  橙子yuan  阅读(22)  评论(0)    收藏  举报