Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The following code is considered invalid by the compiler:

class Foo {
    void foo(String foo) { ... }
}

class Bar extends Foo {
    @Override
    void foo(Object foo) { ... }
}


I think that this is described in the JLS 8.4.8.1: "The signature of m1 is a subsignature (§8.4.2) of the signature of m2." and in 8.4.2: "the bounds of corresponding type variables are the same".

My question is: why can't the parameter in the subtype (Bar) be a supertype of the parameter in the supertype (Foo). In the example Object is a supertype of String. As far as I can see allowing this wouldn't violate the Liskov Substitution Principle.

Is there a scenario in which allowing this would break the code or is it a limitation of the current JLS?
Posted
Comments
Shubhashish_Mandal 10-Jul-13 6:47am    
You get the error because of you try to make an Overloaded method to OverrideMethod using the annotation. If you change the parameter type then the method is no more a override method.So this is not a limitation , this is the beauty of java

1 solution

The answer is plain simple, in Java, for method overriding, you must have the exact signature of the super type. However, if you remove the @Override annotation, your method would be overloaded and your code won't break. This is a Java implementation that ensures that you mean the method implementation should override the implementation of the super type.

Method overriding works in the following way.
Java
class Foo{ //Super Class

  void foo(String string){

    // Your implementation here
  }
}

class Bar extends Foo{

  @Override
  void foo(String string){
    super(); //This method is implied when not explicitly stated in the method but the @Override annotation is present.
    // Your implementation here
  }

  // An overloaded method
  void foo(Object object){
    // Your implementation here
  }
}


The methods shown above are both correct and their implementation can vary.
I hope this helps you.
 
Share this answer
 
Comments
Shubhashish_Mandal 10-Jul-13 8:22am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900