简体   繁体   English

如何将类实例化为变量名?

[英]How to instantiate class to a variable name?

I am working on an assignment, and I have hit one roadblock. 我正在完成一项任务,我遇到了一个障碍。 I am simply calling a string array from another class. 我只是从另一个类调用一个字符串数组。 The code in the other class (named ProductDB) is this: 另一个类(名为ProductDB)中的代码是这样的:

public String[] inventory =  {"java", "jsps", "mcb2", "txtp"};

And in the main application class (named ProductApp) I have this code: 在主应用程序类(名为ProductApp)中,我有以下代码:

public static void showCodes()
{
    System.out.print("  Select from");
    System.out.print("  =>  ");
    for (String show : productDB.inventory)
    {
        System.out.print(show.toUpperCase() + " ");
    }
    System.out.print("  <=");
}

The error I am getting with productDB is 'Cannot find symbol' (I am using NetBeans). 我在productDB遇到的错误是'Cannot find symbol' (我正在使用NetBeans)。

I need to instantiate a variable named productDB correct? 我需要实例化一个名为productDB的变量吗? How do I do this within the ProductApp class level? 如何在ProductApp类级别中执行此操作?

You can set inventory to static , which makes it possible to call it in other classes by ProductDB.inventory . 您可以将inventory设置为static ,这样就可以通过ProductDB.inventory在其他类中调用它。

If you want to use it as you are now, with an instance of ProductDB, simply create an instance variable in class ProductApp (which must be static, since your method is static). 如果您想像现在一样使用它,使用ProductDB实例,只需在ProductApp类中创建一个实例变量(由于您的方法是静态的,因此必须是静态的)。

static ProductDB productDB = new ProductDB();

如果您的productDB是一个类,则需要将inventory成员声明为static

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

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