0

I have this class BindingSample with a method that takes no parameter

public class BindingSample {
  public void printMsg(){
      System.out.println("Binding Sample no parameter");
  }
}

And another class that extends the BindingSample and uses the same method signature but adds a parameter to it

public class application extends BindingSample {

  public void printMsg(int i){
        System.out.println("Changed my value " + i);
  }

  public static void main(String[] args) {
        application app = new application();
        app.printMsg(5);
  }
}

The output is Changed my value 5

Why did it work even if the parameters are different? And why is it called overloading? I don't think it's overriding because to override a method, the method signature and its parameter should be the same.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Dzirus
  • 29
  • 1

2 Answers2

1

Why did it work even if the parameters are different?

You application class has a printMsg method that takes a single int argument. Therefore app.printMsg(5) works.

Note that making the following change will cause your code not to pass compilation:

BindingSample app = new application();
app.printMsg(5);

since now the compiler can't find a printMsg method in the BindingSample class that takes an int argument.

And why is it called overloading? I don't think it's overriding because to override a method, the method signature and its parameter should be the same

Overriding and overloading are two different concepts.

Method overloading occurs when multiple methods share the same name but have different number of arguments or different types of arguments.

Your application class has two printMsg methods (one inherited from its super class) with a different number of arguments. Hence this is method overloading.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Overloading means just the names of the methods should be same. Everything else can be different (e.g. arguments, return types, throwable exceptions etc). As both the methods in the example have same name, it's called Overloading.

The reason why it works is, Overloading is compile time phenomena, compiler just checks for accessibility of the method to the object that's calling it. As you are instantiating application class and calling printMsg method with int argument. It works fine because of the method being present in the class (or being accessible to that object).

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102