内部类

应用场景

  1. 封装性 只能通过外部类访问到内部类,外部类在实例化内部类时可以做一些判断
  2. 通过内部类可以间接实现多继承,可以通过内部类区分出具体调用的是哪个类继承过来的方法,即使父类之前出现同名方法也不担心

普通内部类

定义在类中. 内部类和外部类可以互相访问其属性


class Person {
    private String idCard;
    static String name;


    //外部类方法 可以直接访问内部类实例的私有属性
    void work(){
        System.out.println(new PetDog().age);
    }

    //普通内部类 宠物
    class PetDog{
        String name;
        private int age;

        //内部类可以访问外部类的私有属性: 外部类名.this.属性
        void say(){
            System.out.println(Person.this.name+" "+ this.name + Person.this.idCard);
        }
    }

内部类只能通过外部类访问到. (两种实例化方式)

        Person.PetDog petDog = person.new PetDog();
        Person.PetDog petDog1 = new Person().new PetDog();

局部内部类

定义在方法中,作用于方法内部

    //外部类方法 可以直接访问内部类实例的私有属性
    void work(){
        System.out.println(new PetDog().age);
        int a;
        //局部内部类. 只作用于方法的内部.
        class Test{

        }
    }

匿名内部类

只使用1次

        Person person = new Person(){
            @Override
            void work() {
                System.out.println("work方法调用 我是匿名内部类");
            }
        };
        person.work();//sout: work方法调用 我是匿名内部类

静态内部类

    //静态内部类. 作为一个静态内部类对象,不能访问外部类的实例方法
    static class Personal{
        String val;
    }

完整代码

package com.demo02;

/**
 * 内部类学习
 */
public class Main {
    public static void main(String[] args) {

        /**
         * 实例化内部类 必须先实例化外部类
         */
        Person person = new Person();
        Person.PetDog petDog = person.new PetDog();
        Person.PetDog petDog1 = new Person().new PetDog();
        person.work2();
    }
}

/**
 * 使用多个内部类继承不同父类,可以使外部类间接的实现多继承.
 */
class Person {
    private String idCard;
    static String name;


    //外部类方法 可以直接访问内部类实例的私有属性
    void work(){
        System.out.println(new PetDog().age);
        int a;
        //局部内部类. 只作用于方法的内部.
        class Test{

        }
    }

    //普通内部类 宠物
    class PetDog{
        String name;
        private int age;

        //内部类可以访问外部类的私有属性 外部类名.this.属性
        void say(){
            System.out.println(Person.this.name+" "+ this.name + Person.this.idCard);
        }
    }


    //静态内部类. 作为一个静态内部类对象,不能访问外部类的实例方法
    static class Personal{
        String val;
    }

    //匿名内部类。 只使用1次,没有构造方法
    void work2(){
        Person person = new Person(){
            @Override
            void work() {
                System.out.println("work方法调用 我是匿名内部类");
            }
        };
        person.work();//sout: work方法调用 我是匿名内部类
    }


}

posted on 2021-11-23 15:27  快乐撸代码  阅读(71)  评论(0编辑  收藏  举报

导航