toString方法用Java调用 [英] toString Method Call in Java
问题描述
可能重复:
为什么在打印对象时调用toString()方法?
我在下面有这段代码。我使用Room Class 中的 toString方法了解除输出之外的所有其他内容。在 HotelMain 类中,我刚刚调用了酒店类中的 displayRooms Method 。但是,当我运行程序时,toString输出显示在控制台中。
I have this piece of code below. I understand everything else except the output using the toString method in the Room Class . In the HotelMain Class, I just called the displayRooms Method that was in the Hotel Class. But, when I ran the program, the toString output was shown in the console.
如果我是对的,则toString()是对象中值的文本表示。但是,我不确定我在哪里调用toString方法。
If I'm right toString() is the textual representation of the value in the object. But, I'm not sure where I called the toString method.
有人可以解决我的困境吗?谢谢。
Can someone solve my dilemma? Thank You.
酒店等级
public class Hotel {
private String hotelName;
private Room[] rooms;
public Hotel(String hotelName, int numberOfRooms) {
this.hotelName = hotelName;
this.rooms = new Room[numberOfRooms];
}
public void addRooms(Room room) {
int position = -1;
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom == null) {
position = i;
break;
}
}
if (position != -1) {
rooms[position] = room;
System.out.println("New room added at postion " + position);
} else {
System.out.println("Addition of room failed.");
}
}
public void displayRooms() {
System.out.println("The Hotel: " + this.hotelName + " has the following rooms.");
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
}
}
房间等级
public class Room {
private int roomNumber;
private int numberOfBeds;
private boolean smokingOrNonSmoking;
public Room() {
}
public Room(int roomNumber, int numberOfBeds, boolean smokingOrNonSmoking) {
this.roomNumber = roomNumber;
this.numberOfBeds = numberOfBeds;
this.smokingOrNonSmoking = smokingOrNonSmoking;
}
@Override
public String toString() {
return "Room [roomNumber=" + roomNumber + ", numberOfBeds="
+ numberOfBeds + ", smokingOrNonSmoking=" + smokingOrNonSmoking
+ "]";
}
}
Hotel Main
public class HotelMain {
public static void main(String[] args) {
Hotel hotel = new Hotel("MahaRani Chain of Hotels", 10);
Room room1 = new Room(4, 2, true);
Room room2 = new Room(2, 1, false);
Room room3 = new Room(6, 3, true);
Room room4 = new Room(6, 4, false);
hotel.addRooms(room1);
hotel.addRooms(room3);
hotel.addRooms(room4);
hotel.addRooms(room2);
hotel.displayRooms();
}
}
控制台
推荐答案
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
您的 displayRooms()中有以上代码
方法。它打印 tempRoom
,这是 Room
的引用,因此它调用 toString()
在 Room
类中重写的方法。
You have the above code in your displayRooms()
method. It prints tempRoom
, which is a reference of Room
, and hence it calls toString()
method overridden in the Room
class.
这篇关于toString方法用Java调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!