jai
jai

Reputation: 547

Why do I get a compilation error when I try to have two methods with the same name and parameter type?

If i change the byte to int I get a compiler error. Could you explain the problem?

public class A {
   protected int xy(int x) { return 0; }
}

class B extends A {
   protected long xy(int x) { return 0; } //this gives compilor error
   //protected long xy(byte x) { return 0; } // this works fine
}   

Upvotes: 5

Views: 164

Answers (7)

rivka
rivka

Reputation: 21

You are trying to write two methods with the same name and input parameters, that is not possible.

Look at the following two methods:

float met(){
  return 4.5;
}

double met(){
  return 5.4;
}

If we would write this line then

int x = (int)met();

what method would be called?

It is not possible to decide, therefore this situation is not permitted.

Upvotes: 2

M.Faizal
M.Faizal

Reputation: 450

Overiding method should return a type that can be substituted for the type returned by overriden method

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075635

If i change the byte to int I get a compiler error.

If you do that, you have this:

public class A {
   protected int xy(int x) { return 0; }
}

class B extends A {
   protected long xy(int x) { return 0; }
}   

...and the only difference in the xy methods is their return type. Methods cannot be differentiated solely by their return types, that's the way Java is defined. Consider this:

myInstance.xy(1);

Which xy should that call? long xy(int x) or int xy(int x)?

If your goal is to override xy in B, then you need to make its return type int in order to match A#xy.

Upvotes: 6

Lukas Warsitz
Lukas Warsitz

Reputation: 1239

Because when you change the byte into int the Instance which calls the method doesn't know which method is meant. The overwritten one or the old one?

Thats why it's not allowed to have the same signatures (method name, type of parameters and amount of parameters). Just as an information: The return type is not part of the signature.

Upvotes: 0

saravanakumar
saravanakumar

Reputation: 1777

You can differentiate methods by parameters and names only.

     both methods are in same class B

     b.xy(byte x) or b.xy(int x) is called for input xy(0) or xy(1)

Upvotes: 1

markubik
markubik

Reputation: 671

That's because if You change byte to int You will have method with the same signature in base and sub class (same method name and parameter type) and therefore return type should be the same as well. Because is not (int and long) it will give You error

Upvotes: 1

Keerthivasan
Keerthivasan

Reputation: 12890

You can't have two methods with same signature in a Class though the methods are placed separately in different classes in the same inheritance tree. i.e. Base class and sub class

Note : Just return types can't make the compiler understand the difference in methods. return type is NOT included in the method signature as well

Upvotes: 2

Related Questions