Reputation: 13
I am not understanding the Concept of Passing objects as parameters. Below is an example. My question is how can I invoke my PrintTime method? If my understanding is correct: the first method (Time) is a constructor with no parameters but the PrintTime is a method with an object as a parameter. How can I invoke it?
public class Time {
int hour, minute;
double second;
public Time() {
this.hour= 0;
this.minute= 0;
this.second= 0.0;
}
public static void printTime(Time t){
System.out.println(t.hour+ ":"+ t.minute+ ":"+ t.second);
}
public static void main(String[] args) {
Time t1 = new Time();
t1.hour= 11;
t1.minute= 8;
t1.second= 3.14159;
System.out.println(t1);
}
}
Upvotes: 0
Views: 57
Reputation: 48258
Yes, public Time() {
is a constructor and
public static void printTime(Time t){
is a method, to call this method (you have defined static) you need to do:
public static void main(String[] args) {
Time t1 = new Time();
t1.hour= 11;
t1.minute= 8;
t1.second= 3.14159;
Time.printTime(t1); /// <--< here
}
Upvotes: 0
Reputation: 279
In your main method you can call printTime(t1);
The paramter t in your printTime method is an reference to the Time object you will pass into the method.
Upvotes: 2