3

I have classes as follows

public class Useful 
{
    public void f(Object a)
    {
        System.out.println("In base f");
    }

    public void g(String a)
    {
        System.out.println("In base g");
    }
}

public class MoreUseful extends Useful 
{
    public void f(String a)
    {
        System.out.println("In derived f");
    }

    public void g(Object a)
    {
        System.out.println("In derived g");
    }
}

I am trying to override base class method but I am changing the parameters in derived class. in method MoreUseful.f() I am using subclass parameter (String) as against Object in base class. in method MoreUseful.g() I am using superclass parameter (Object) as against String in base class.

Is it possible to override these way? Which of the above two cases will be correct overriding?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sachin
  • 247
  • 4
  • 16
  • 26
  • Whenever it comes to overriding always use the annotation `@Override` then the compiler itself will tell you if you cannot do that or if something is wrong. http://stackoverflow.com/q/94361/738746 – Bhesh Gurung Apr 11 '14 at 14:54

2 Answers2

0

No, that's not possible, and would be a violation of the LSP.

By inheriting from a class, you express that your subclass MoreUseful is actually a Useful and therefore exposes all the functionality that Useful exposes. If you removed the ability to invoke f with an object, you'd break that promise.

You are free to overload f so that you have an f(String s) method though.

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
0

The g() method is indeed overriden. f(), however, is not overriden - it's overloaded. An easy way to verify this is to add @Override on each method you intend to override - if it results in a compilation error, you aren't overriding properly.

Mureinik
  • 297,002
  • 52
  • 306
  • 350