我有这个课

package com.rafael;

public class Vehicle {

    public class InnerVehicle {
        InnerVehicle() {
            System.out.println("This is InnerVehicle");
        }
    }
}


并且在主要功能上

import com.rafael.Vehicle;

public class VehicleTest {
    public static void main(String[] args) {
        Vehicle v = new Vehicle();
        Vehicle.InnerVehicle iv = v.new InnerVehicle();
    }
}


但这总是给我这个错误:


Java:InnerVehicle()在com.rafael.Vehicle.InnerVehicle中不公开;
无法从外部包访问

最佳答案

使内部类public static

否则,您需要外部类的对象来创建内部类的实例,如Tim Biegeleisen所述

并将内部类的构造函数也设为public

就像是:

public class Vehicle {
    public static class InnerVehicle {
        public InnerVehicle() {
            System.out.println("This is InnerVehicle");
        }
    }
}

10-04 11:40