Java调用tostring方法分析,toString方法用Java调用

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.

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.

Hotel Class

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);

}

}

}

Room Class

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();

}

}

Console

FsFqD.png

解决方案

Room tempRoom = rooms[i];

if (tempRoom != null) {

System.out.println(tempRoom);

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值