public class Reservation {
int guestCount;
int restaurantCapacity;
boolean isRestaurantOpen;
boolean isConfirmed;
public Reservation(int count, int capacity, boolean open) {
if (count < 1 || count > 8) {
System.out.println("Invalid reservation!");
}
guestCount = count;
restaurantCapacity = capacity;
isRestaurantOpen = open;
}
public void confirmReservation() {
if (restaurantCapacity >= guestCount && isRestaurantOpen) {
System.out.println("Reservation confirmed");
isConfirmed = true;
} else {
System.out.println("Reservation denied");
isConfirmed = false;
}
}
public void informUser() {
if (!isConfirmed) {
System.out.println("Unable to confirm reservation,
please contact restaurant.");
} else {
System.out.println("Please enjoy your meal!");
}
}
public static void main(String[] args) {
// Create instances here
Reservation mesa2 = new Reservation (2,10,true);
Reservation mesa12 = new Reservation (12,10,true);
Reservation mesa4 = new Reservation (4,10,false);
mesa2.confirmReservation();
mesa2.informUser();
//mesa12.confirmReservation();
//mesa12.informUser();
//mesa4.confirmReservation();
//mesa4.informUser();
}
}
I’ve reformatted your code here so it’s a bit easier to understand what’s going on. We know that the main method is automatically called when we run our code. That means this is the first line that is executed.
Reservation mesa2 = new Reservation (2,10,true);
We create a new instance of Reservation
named mesa2
. When we create this instance, the Reservation()
constructor is run. if (count < 1 || count > 8)
is false for this instance because count = 2
in this case. Therefore, its instance variables get assigned values and we move on to the next line of code in the main method.
The next line is as follows.
Reservation mesa12 = new Reservation (12,10,true);
This time, we are also creating another instance of Reservation
, this time named mesa12
. When we create this instance, the Reservation()
constructor is run again. if (count < 1 || count > 8)
is true this time because count = 12
. Therefore, the message "Invalid reservation!"
is printed out, its instance variables get assigned values, and we continue to the next line of code in the main method.
Because if (count < 1 || count > 8)
is in your constructor, it runs every time a new object is created. You are creating mesa12
before you call instance methods on mesa2
, that’s why you’re getting Invalid reservation!
first.