Java自定义类

时间:2015-10-11 01:48:03

标签: java class arraylist

import java.util.ArrayList;
public class Watch{

// instance variables for the class watch
private String name;    
private long serial_no;
private String desc;
private String color;
private double price;
private double weight;
private int hour;
private int min;
private int sec;

ArrayList<Watch> watchStore = new ArrayList<Watch>();

public void addWatch(String nme, long s_r, String ds, String cl, double pr, double wg){
    watchStore.add(new Watch(nme, s_r, ds, cl, pr, wg));
}

public String disWatch(){
    return watchStore.get(watchStore) + "";
}

在我的addWatch方法中,我创建了一个new Watch来添加到Watch类内的ArrayList。这可能吗?

2 个答案:

答案 0 :(得分:2)

我想最好有两个类:StoreWatch,其中类Store包含类似ArrayList<Watch> watches;的列表。

班级Store

public class Store {
   private ArrayList<Watch> watches;

   public Store() {
      watches = new ArrayList<>();

      // Add first watch
      watches.add(new Watch(...));
   }
}

班级Watch

public class Watch {
   private String name;    
   private long serial_no;
   private String desc;
   private String color;
   private double price;
   private double weight;
   private int hour;
   private int min;
   private int sec;

   public Watch(...) {
      // ...
   }
}

答案 1 :(得分:0)

是的,为什么不呢?但要制作更多容器类来存储手表(WatchStore)。