简体   繁体   English

实例化新的内部类时,内部类不是公共错误

[英]Inner class is not public error when instantiating new inner class

I have this class 我有这堂课

package com.rafael;

public class Vehicle {

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

And in the main function 并且在主要功能上

import com.rafael.Vehicle;

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

But this always gives me that error: 但这总是给我这个错误:

java: InnerVehicle() is not public in com.rafael.Vehicle.InnerVehicle; Java:InnerVehicle()在com.rafael.Vehicle.InnerVehicle中不公开; cannot be accessed from outside package 无法从外部包访问

Make the inner class public static 使内部类成为public static

Otherwise you need an object of your outer class to creat an instance of the inner as Tim Biegeleisen already mentioned 否则,您需要外部类的对象来创建内部类的实例,如Tim Biegeleisen所述

And make the constructor of your inner class public too 并使内部类的构造函数也public

Something like: 就像是:

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

You were referring to the nested class incorrectly. 您错误地引用了嵌套类。 You can only instantiate the inner class in the context of the containing class: 您只能在包含类的上下文中实例化内部类:

Vehicle v = new Vehicle();
InnerVehicle iv = v.new InnerVehicle();

The syntax you were using was for a static nested class, in which case your code would look like this: 您使用的语法是针对静态嵌套类的,在这种情况下,您的代码将如下所示:

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

Vehicle.InnerVehicle iv = new Vehicle.InnerVehicle();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM