Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiler showing error

Following is code

class Hotel {
 public int bookings;
 public void book() {
    bookings++;
 }
}

public class Test extends Hotel{
 public void book() {
    bookings--;
 }

 public void book(int size) {
    book();
    super.book();
    bookings += size;
 }

 public static void main(String... args) {
   Hotel hotel = new Test();
   hotel.book(2);  // Compiler show error
    System.out.print(hotel.bookings);
 }        
}       

Erorr: method book in class javaapplication1.Hotel cannot be applied to given types;

required: no arguments

found: int

reason: actual and formal argument lists differ in length

Why compiler is complaining? which rule of Method Overloading/Overriding compiler is applying?

Your response will be Appreciated !!!

like image 953
Prashant Shilimkar Avatar asked Nov 23 '25 11:11

Prashant Shilimkar


2 Answers

hotel is of type Hotel, which doesn't have book(int) method.

If you want to call book(int) you need to change (or cast) hotel's type to Test

   Test hotel = new Test();
   hotel.book(2);  // No error
like image 120
BobTheBuilder Avatar answered Nov 25 '25 00:11

BobTheBuilder


You are using overloading which is a compile time polymorphism. So when the compiler sees hotel.book(2); it expects the Hotel's version of book method (remember its compile time). Since the hotel's version of book method does not contain any arguments, it considers this call as invalid and hence the error.

like image 40
aryann Avatar answered Nov 25 '25 00:11

aryann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!