- 我使用“价格”和“销售额”字段定义了“类产品”。
- 然后,我创建了一个“Product”类型的数组: 产品productArray[] = 新产品[100]
- 然后,我使用包含 100 行和 2 列的 Excel 表格中的数据填充此数组(A 列:“价格”,B 列:“销售”)
我想直接访问不同产品的价格,比如第97行的产品价格。 也就是说,我想做类似的事情 double 变量=productArray[97].price
有没有办法在java中做到这一点?
非常感谢您的帮助! 预先感谢您。
最佳答案
您应该为变量创建 getter 和 setter 方法,因为封装是保护变量的一个很好的 OOP 概念。
考虑以下场景,该场景与您正在做的事情类似,您有一个 Product 类。
我将使用外星人类:
public class Alien{
//Properties of aliens
int numOfFingers;
String name;
String color;
public Alien(int num, String name, String color)
{
this.numOfFingers = num;
this.name = name;
this.color = color;
}
}//End of alien class
包含数组的类:
public class DetailExtractor {
//Arraycontaining alien objects
Alien[] alienRegister = new Alien[100];
public static void main(String[] args){
//Populating the array
alienRegister[0] = new Alien(3, "Zorg", "Blue");
alienRegister[1] = new Alien(5, "Chad", "Purple");
//Retrieving a property, say name of second alien...
System.out.println(alienRegister[1].name);
}
}
关于java - 当对象是数组的一部分时直接访问对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445522/