-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path30_toStringMethod
More file actions
45 lines (37 loc) · 985 Bytes
/
30_toStringMethod
File metadata and controls
45 lines (37 loc) · 985 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//toString() = special method that all objects inherit,
// that returns a string taht "textually represents" an object,
// can be used both implicitly and explicitly
<Main.java>
public class Main {
public static void main(String[] args){
Car car = new Car();
System.out.println(car.make);
System.out.println(car.model);
System.out.println(car.color);
System.out.println(car.year);
/* >> Ford
Mustang
red
2021
*/
System.out.println(car);
//>> Car@27d6c5e0 //Address of car object in memory
System.out.println(car.toString()); //before edit in <Car.java>
//>> Car@27d6c5e0
System.out.println(car); //after edit in <Car.java>
/*>>Ford
Mustang
red
2021*/
}
}
<Car.java>
public class Car {
String make = "Ford";
String model = "Mustang";
String color = "red";
int year =2021;
public String toString(){
return make + "\n"+model+"\n"+color+"\n"+year;
}
}