Java 内部类(嵌套类)和局部类

2020-08-26  本文已影响0人  有梦想的狼

嵌套类

嵌套类又分为:内部类和静态嵌套类。

内部类

public class Company {

    private String name;
    
    public Company (String name) {
        this.name = name;
    }
    
    public void fire(Employee e) {
        System.out.println(this.name + "fire" + e.no);
    }
    
    public class Employee {
        
        private int no;
        
        public Employee(int no) {
            this.no = no;
        }
        
        public void show() {
            System.out.println(Company.this.name + ":" + this.no);
        }
    }   
}
Company company = new Company("阿里巴巴");
Employee employee = company.new Employee(100);
company.fire(employee);
employee.show();

打印结果:

阿里巴巴fire100
阿里巴巴:100

静态嵌套类

public class Person {
    
    private int age;
    
    private static String name;
    
    private static void run() {
        System.out.println("Person - run");
    }
    
    public static class Car{
        public void print() {
            System.out.println(name);
            run();
        }
    }
}

什么情况下使用嵌套类?

  1. 如果类A只用在类C内部,可以考虑将类A嵌套到类C中
    • 封装性更好
    • 程序包更加简化
    • 增强可读性、维护性
  2. 如果类A需要经常访问类C的非公共成员,可以考虑将类A嵌套到类C中
    另外也可以根据需要将类A影藏起来,不对外暴露
  3. 如果需要经常访问非公共的实例成员,则设计成内部类(非静态嵌套类),否则设计成静态嵌套类
    如果必须先有C实例,才能创建A实例,那么可以将A设计为C的内部类

局部类

public class TestLocalClass {

    private int a = 1;
    private static int b = 2;
    private static void test1() {}
    private void test2() {}
    
    public void test3() {
        int c = 2;
        
        class LocalClass {
            static final int d = 4;
            void test4() {
                System.out.println(a + b + c + d);
                test1();
                test2();
            }
        }
        
        new LocalClass().test4(); 
    }
}
上一篇 下一篇

猜你喜欢

热点阅读