如何通过for循环访问子类的静态变量。 [英] How do I access a static variable of a subclass through a for loop.
问题描述
嗨!
我有一个名为product的超类和3个子类,叫做Laptop,Web和Microphone。在每个子类中,创建了一个静态变量,用于计算每个类的产品数量。我创建了一个数组列表,显示每个产品,但我的问题是,不知道如何调用分配给每个对象的静态变量。
我尝试过:
子类笔记本电脑的页面:
Hi!
I have a superclass called product and 3 subclasses called Laptop, Web and Microphone. In each subclass a created a static variable that counts the number of products from each class. I created an Array list that shows the products from each but my problem is that a don't know how to call the static variable assigned to each object.
What I have tried:
The page of subclass laptop:
public class laptop extends Products {
static int stock=0;
public laptop(String name, String color, Double price, Double discount) {
super(name, color, price, discount);
stock++;
public static int getStock() {
return stock;
}
}
创建对象的数组列表的类:
The class of the Array List that creates the objects:
<pre>ArrayList <Products> catalog = new ArrayList<>();
catalog.add( new web("web", "red", 145.0, 1.0));
catalog.add( new microphone("microphone", "red", 145.0, 1.0));
catalog.add( new laptop("laptop", "red", 145.0, 1.0));
所以,如果我打电话给web.getStock,一切正常,我可以访问股票。但是,如果我想使用for循环显示列表,我真的不知道如何访问每个产品的库存。
So, If I would call web.getStock everything works fine and I can access the stock. But if I want to display the list using a for loop I don't really know how to access the stock of each product.
<pre> for(int i=0; i<catalog.size(); i++){
System.out.println(catalog.get(i).name + " " + (Here! I don't know how to acces the static variable of each catalog.get(i).name);
推荐答案
为什么不为每种产品类型使用单独的列表,因此您只需使用 ArrayList.size() [ ^ ]获取计数?
Why not use separate lists for each product type, so you can just use ArrayList.size()[^] to get the count?
在Product
类中定义一个抽象方法,并在派生的方法中覆盖它。例如
Define an abstract method in theProduct
class and override it in the derived ones. For instance
abstract class Product
{
String name;
public Product(String name)
{
this.name = name;
}
public abstract int getStock();
}
class Laptop extends Product
{
static int stock = 0;
public Laptop(String name)
{
super(name);
++stock;
}
@Override
public int getStock()
{
return stock;
}
}
//...
// in main method
ArrayList <Product> catalog = new ArrayList<Product>();
catalog.add( new Laptop("foo") );
catalog.add( new Laptop("goo"));
System.out.println( catalog.get(1).getStock() );
>
这篇关于如何通过for循环访问子类的静态变量。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!