导入
内部类和嵌套类
通过在其他类中定义类,学习有效地组织代码,以提高封装性、分组相关逻辑,并创建简洁的一次性实现。
1public class CPU { 2 private static final int MAX_CORES = 8; 3 private String model; 4 5 public CPU(String model) { 6 this.model = model; 7 } 8 9 // 静态嵌套类 10 public static class Cache { 11 private int sizeKB; 12 13 public Cache(int sizeKB) { 14 this.sizeKB = sizeKB; 15 } 16 17 public void printInfo() { 18 // 可以访问外部类的静态成员 19 System.out.println("最大核心数(来自外部类): " + MAX_CORES); 20 21 // 无法直接访问 'model',因为它是实例变量 22 // System.out.println(model); // 编译时错误 23 24 System.out.println("缓存大小: " + sizeKB + "KB"); 25 } 26 } 27 28 public static void main(String[] args) { 29 // 我们可以在没有 CPU 实例的情况下实例化嵌套类 30 CPU.Cache l1Cache = new CPU.Cache(512); 31 l1Cache.printInfo(); 32 } 33}
1public class Car { 2 private String model; 3 private boolean isEngineRunning = false; 4 5 public Car(String model) { 6 this.model = model; 7 } 8 9 // 成员内部类(非静态) 10 public class Engine { 11 public void start() { 12 // 我们可以直接访问外部实例的私有字段 13 if (!isEngineRunning) { 14 isEngineRunning = true; 15 System.out.println(model + " 发动机已启动。"); 16 } else { 17 System.out.println(model + " 发动机已经运行。"); 18 } 19 } 20 21 public void printModel() { 22 // 显式通过 'Car.this' 引用外部实例 23 System.out.println("发动机属于: " + Car.this.model); 24 } 25 } 26 27 public static void main(String[] args) { 28 Car myCar = new Car("轿车"); 29 30 // 我们需要 Car 的实例才能创建 Engine 31 Car.Engine myEngine = myCar.new Engine(); 32 33 myEngine.start(); 34 myEngine.printModel(); 35 } 36}
1public class PasswordManager { 2 3 public void validate(String password) { 4 final int minLength = 8; // 有效最终变量 5 6 // 在方法内部定义的局部类 7 class Validator { 8 public void check() { 9 // 访问方法参数(也是有效最终的) 10 if (password.length() < minLength) { 11 System.out.println("错误:密码太短。"); 12 } else { 13 System.out.println("密码已接受。"); 14 } 15 } 16 } 17 18 // 我们只能在此方法内使用 Validator 19 Validator v = new Validator(); 20 v.check(); 21 } 22 23 public static void main(String[] args) { 24 PasswordManager pm = new PasswordManager(); 25 pm.validate("secret"); 26 } 27}
1// 一个简单的接口 2interface Greeter { 3 void greet(String name); 4} 5 6public class Demo { 7 public static void main(String[] args) { 8 // 实现 Greeter 的匿名类 9 Greeter englishGreeter = new Greeter() { 10 @Override 11 public void greet(String name) { 12 System.out.println("你好," + name); 13 } 14 }; 15 16 englishGreeter.greet("Java 学习者"); 17 } 18}