Inner class is not public 实例化新的 inner class 时出错
Inner class is not public error when instantiating new inner class
我有这个class
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() is not public in com.rafael.Vehicle.InnerVehicle;
cannot be accessed from outside package
制作内classpublic static
否则,您需要外部对象 class 来创建内部实例,正如 Tim Biegeleisen 已经提到的那样
并使您的内部 class public
的构造函数也成为
类似于:
public class Vehicle {
public static class InnerVehicle {
public InnerVehicle() {
System.out.println("This is InnerVehicle");
}
}
}
您指的是嵌套 class 不正确。您只能在包含 class:
的上下文中实例化内部 class
Vehicle v = new Vehicle();
InnerVehicle iv = v.new InnerVehicle();
您使用的语法用于静态嵌套 class,在这种情况下,您的代码将如下所示:
public class Vehicle {
static public class InnerVehicle {
InnerVehicle() {
System.out.println("This is InnerVehicle");
}
}
}
Vehicle.InnerVehicle iv = new Vehicle.InnerVehicle();
我有这个class
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() is not public in com.rafael.Vehicle.InnerVehicle; cannot be accessed from outside package
制作内classpublic static
否则,您需要外部对象 class 来创建内部实例,正如 Tim Biegeleisen 已经提到的那样
并使您的内部 class public
的构造函数也成为
类似于:
public class Vehicle {
public static class InnerVehicle {
public InnerVehicle() {
System.out.println("This is InnerVehicle");
}
}
}
您指的是嵌套 class 不正确。您只能在包含 class:
的上下文中实例化内部 classVehicle v = new Vehicle();
InnerVehicle iv = v.new InnerVehicle();
您使用的语法用于静态嵌套 class,在这种情况下,您的代码将如下所示:
public class Vehicle {
static public class InnerVehicle {
InnerVehicle() {
System.out.println("This is InnerVehicle");
}
}
}
Vehicle.InnerVehicle iv = new Vehicle.InnerVehicle();