我有这个班级
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中不公开; 无法从外包装
访问
答案 0 :(得分:1)
制作内部班级public static
否则你需要你的外部类的一个对象来创建一个内部的实例,如Tim Biegeleisen已经提到的那样
并使你的内部类public
的构造函数
类似的东西:
public class Vehicle {
public static class InnerVehicle {
public InnerVehicle() {
System.out.println("This is InnerVehicle");
}
}
}
答案 1 :(得分:0)
您错误地引用了嵌套类。您只能在包含类的上下文中实例化内部类:
Vehicle v = new Vehicle();
InnerVehicle iv = v.new InnerVehicle();
您使用的语法是静态嵌套类,在这种情况下,您的代码将如下所示:
public class Vehicle {
static public class InnerVehicle {
InnerVehicle() {
System.out.println("This is InnerVehicle");
}
}
}
Vehicle.InnerVehicle iv = new Vehicle.InnerVehicle();