【问题标题】:Using setDate for User defined class.. Java对用户定义的类使用 setDate.. Java
【发布时间】:2017-03-18 16:32:53
【问题描述】:

我创建了一个用户定义的类 Date 具有 3 个属性,日、月、年,然后我将 Date 类调用到我的 Appointment 类中,它变成了私有 Date 日期..现在我需要使用 setter 和 getter..我知道如何为单个属性创建 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);

【问题讨论】:

  • " 我知道如何为单个属性创建 setter 和 getter,但对于像 setDate 这样的整个类,我将其调用到我的 Appointment 类中,我不知道该怎么做" 这句话对我来说毫无意义,因为您尝试设置的变量类型没有区别。
  • @Tom 对不起,我的意思是我知道如何将 setter 和 getter 用于 Strings 和 Integeter,但不适用于用户定义的具有 3 个属性的 Date 类
  • 这部分对我来说毫无意义。这里没有区别。这就像说我知道如何坐在椅子上,但不知道如何坐在沙发上。

标签: java arrays eclipse clone


【解决方案1】:

好吧,你知道如何对整数使用 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)

你可以用同样的方法制作一个setter!它看起来像:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 2022-01-26
    • 1970-01-01
    • 2015-11-04
    • 2022-12-08
    相关资源
    最近更新 更多