为何无法实例化Java嵌套内部类?Eclipse报错求助
问题原因
你定义的Vehicle和Car是非静态内部类,这类内部类的实例必须依赖外部类Inheritance的实例才能创建。但main方法是静态方法,属于类本身而非实例,所以在静态方法里直接new Vehicle()或new Car()时,编译器找不到对应的外部类实例,就会抛出你看到的错误。
解决方案
下面两种方法都能解决问题,且不会丢失变量:
方案1:通过外部类实例创建内部类对象
先创建外部类Inheritance的实例,再用这个实例来初始化内部类:
public static void main(String[] args) { // 先创建外部类实例 Inheritance outerInstance = new Inheritance(); // 通过外部类实例创建内部类对象 Vehicle v1 = outerInstance.new Vehicle(); v1.setLicensePlate("P125ADS"); Car c1 = outerInstance.new Car(); c1.setLicensePlate("P124ABS"); // 验证变量正常工作 System.out.println("Vehicle车牌:" + v1.licensePlate); System.out.println("Car车牌:" + c1.getLicensePlate()); }
这种方法适合内部类需要访问外部类非静态成员的场景。
方案2:将内部类改为静态内部类(推荐)
给Vehicle和Car加上static修饰,把它们变成静态内部类。静态内部类属于外部类本身,不需要依赖外部类实例就能创建对象,完全适配静态方法的使用场景:
package moreAboutOOP; public class Inheritance { // 给Vehicle加static public static class Vehicle { protected String licensePlate = null; public void setLicensePlate(String license) { this.licensePlate = license; } } // 给Car加static public static class Car extends Vehicle { int numberOfSeats = 0; public int getNumberOfSeats() { return (this.numberOfSeats); } public String getLicensePlate() { return this.licensePlate; } } public static void main(String[] args) { // 现在可以直接创建对象,和普通类完全一样 Vehicle v1 = new Vehicle(); v1.setLicensePlate("P125ADS"); Car c1 = new Car(); c1.setLicensePlate("P124ABS"); // 验证变量正常工作 System.out.println("Vehicle车牌:" + v1.licensePlate); System.out.println("Car车牌:" + c1.getLicensePlate()); } }
你的代码里内部类不需要访问外部类的非静态成员,所以这个方案更简洁高效。
内容的提问来源于stack exchange,提问作者Sabathiel
相关产品推荐
相关产品推荐

