可能重复:
为什么当我打印的对象被称为toString()方法?
我有这片下面的代码。 我明白了一切,除了使用客房类toString方法的输出别人。 在HotelMain类,我只是叫displayRooms方法是在酒店等级 。 但是,当我运行该程序时,输出的toString结果显示在控制台中。
如果我是正确的toString()是对象的值的文本表示。 但是,我不知道,我叫toString方法。
谁能解决我的难题呢? 谢谢。
酒店等级
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
+ "]";
}
}
酒店主
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();
}
}
安慰