使用setDate for User defined class .. Java

时间:2017-03-18 16:32:54

标签: java arrays eclipse clone

我创建了一个用户定义的类Date,包含3个属性,day,month,year,然后我将Date类调用到我的Appointment类中,它变成了私有Date日期..现在我需要使用setter和getters ..我知道如何为单个属性创建setter和getter但是对于像setDate这样的整个类,我调用了我的Appointment类,我不知道该怎么做..这是我试图做的但值不是改变

ArrayList<Appointment> ai= new ArrayList();
        Appointment ap= new Appointment(date,time);
        ap.setDoctor_id("1");
        ap.setMedication("w");
        ap.setPatient_id("3");
        ap.setProblem("pro");
        ap.setRoom("ss");
        ai.add(ap);

        Appointment o=null;
        try
        {
            //Creating a deep clone of ap and assigning it to o

            o = (Appointment) ap.clone1();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
        date.setDay(4);
        date.setMonth(9);
        date.setYear(2000);
        o.setDate(date);

        o.setRoom("pp");
        o.setProblem("Happiness");
        o.setMedication("Anti-Happiness pills");
        ai.add(o);

        Appointment t= (Appointment) o.clone1();

        date.setDay(1);
        date.setMonth(12);
        date.setYear(18);
        t.setDate(date);
        t.setRoom("p");
        t.setProblem("depressin");
        t.setMedication("Anti-depression pills");

        ai.add(t);

1 个答案:

答案 0 :(得分:0)

嗯,你知道如何使用setter作为整数,你可以这样做:

private int setDay(int day) {
 this.day = day
}

您还知道如何创建新对象:

Appointment ap= new Appointment(date,time);

对于可能看起来像的构造函数:

public Appointment(Date date, Time time) {
  this.date = date;
  this.time = time;
}

所以如果你的日期构造函数看起来像:

public Date(int day, int month, int year) {
  this.day = day;
  this.month = month;
  this.year = year;
}

您可以采用与新约会类似的方式创建新日期:

Date newDate = new Date(day, month, year)

你可以用同样的方式制作一个制定者!它看起来像是:

private setDate(int day, int month, int year) {
   this.date = new Date(day, month, year);
}

或:

private setDate(Date date) {
   this.date = date;
}

对于上述内容,您必须先将日期设为首字母,以便将其称为:

Date newDate = new Date(day,month,year);
setDate(newDate);