Java:从另一个类调用值

时间:2017-03-13 10:22:52

标签: java arrays eclipse class

好的所以我必须创建一个带有属性私有日期和私有时间的约会类,它引用已经创建的具有相同名称的类(日期,时间)..但事情是..我的日期类有属性日,月,年和时间有小时,分钟,我已经设置了它们的值..如何在约会类中使用私人约会日期并获取两个类的属性值..如果问题是一个,我很抱歉有点令人困惑的东西..我一直试图想出这个,但我甚至不知道这甚至叫做什么。它是否被称为在新的类中声明另一个类或什么?请帮忙。感谢

3 个答案:

答案 0 :(得分:0)

不知道你真正想做什么,发布一些代码。

无论如何,听起来你需要在主类上实例化Date类和Time类才能使用它。

Date d=new Date();
Time t=new Time();

那将是评论,但我还没有足够的代表。遗憾。

答案 1 :(得分:0)

如果我理解正确,你的课程看起来像这样:

  class Appointment {
    private Date date;
    private Time time;
    }

class Date {
private String day;
private String month;
private int year;
}

class Time {
private int hour;
private int minutes;
}

你已经有一个关于时间和日期的实例,每个实例都设置了它们的值,现在你想在约会类中设置这些日期和时间值吗?

如果是,您可以使用Setter或构造函数。

如果你使用setter,你的Appointment类看起来像这样:

 class Appointment {
    private Date date;
    private Time time;

    public void setDate(Date date){
        this.date = date;
    }
    public void setTime(Time time) {
        this.time = time;
    }
}

然后你会使用上面的代码:

public static void main(String[] args){
  Date yourDate = new Date("Monday",2,1993); //the date object which you already have
  Time yourTime = new Time(5,6); // the time object that you already have

  Appointment yourAppointment = new Appointment(); //creating an empty Appointment object
  yourAppointment.setDate(yourDate); //setting your created date in appointment
  yourAppointment.setTime(yourTime); //setting your created time in appointment
}

或者您可以在约会类中使用构造函数而不是setter。 现在,约会课程看起来像:

 class Appointment {
        private Date date;
        private Time time;

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

然后你可以像这样设置日期和时间值:

    public static void main(String[] args){
      Date yourDate = new Date("Monday",2,1993); //the date object which you already have
  Time yourTime = new Time(5,6); // the time object that you already have

  Appointment yourAppointment = new Appointment(yourDate,yourTime); 
}

答案 2 :(得分:0)

如果你的班级有私人信息,你需要有一个“getter”方法来访问其他班级。请在下面找到getter和setter的例子:

#include <NewPing.h>

#define TRIGGER_PIN  8  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     7  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
int p = 3;
void setup() {
  // put your setup code here, to run once:
  pinMode(p,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  int d = sonar.ping_cm();
  Serial.print(d); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  analogWrite(p,d);

}