Java 如何将类实例化为变量名?
我正在做一项任务,我遇到了一个障碍。我只是从另一个类调用字符串数组。另一个类(名为ProductDB)中的代码如下: 在主应用程序类(名为ProductApp)中,我有以下代码:Java 如何将类实例化为变量名?,java,Java,我正在做一项任务,我遇到了一个障碍。我只是从另一个类调用字符串数组。另一个类(名为ProductDB)中的代码如下: 在主应用程序类(名为ProductApp)中,我有以下代码: public static void showCodes() { System.out.print(" Select from"); System.out.print(" => "); for (String show : productDB.inventory) {
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(" <=");
}
publicstaticvoidshowcodes()
{
系统输出打印(“从中选择”);
系统输出打印(=>);
for(字符串显示:productDB.inventory)
{
System.out.print(show.toUpperCase()+);
}
System.out.print(如果您的productDB
是一个类,您需要声明inventory
成员static
您可以将inventory
设置为static
,这使得productDB.inventory
可以在其他类中调用它
如果您想使用ProductDB实例,只需在ProductApp类中创建一个实例变量(它必须是静态的,因为您的方法是静态的)
这要求我公开库存。我照你说的做了,我得到了一个错误“非静态变量productDB不能从静态上下文引用”我刚刚将我的实例变量设置为静态,它已经修复了它,谢谢你的帮助!@user3538320-啊,是的,我没有意识到这个方法是静态的,但我很高兴你发现了这一点。我该怎么做呢所有这些方法都在main中吗?
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(" <=");
}
static ProductDB productDB = new ProductDB();