2

I have a base class with a method called execute :

class A {
    public execute(int a){}
}

I also have a class B, which extends A, but the execute method needs more parameters:

Currently, my solution is using optional parameters :

class B extends A {
    public execute(int a, Object... parameters){
        long b = (long)parameters[0];
        boolean c = (boolean)parameters[1];
        ....
    }
}

This would still be ugly because I must cast on parameters. Are there other options for this situation?

Mario Cervera
  • 671
  • 1
  • 8
  • 19
Viet
  • 3,349
  • 1
  • 16
  • 35
  • Are you expecting a fixed number of parameters for `execute()` ? – Atri Jan 21 '16 at 04:19
  • See [answer](http://stackoverflow.com/questions/965690/java-optional-parameters) by Vitalii Fedorenko, that lists all possible options. – Sabir Khan Jan 21 '16 at 04:56
  • @Atri : i don't need fixed number of parameters, i want to call through by base class. Ex : A a = MyFactory.getInstance(...) , a.execute(...) – Viet Jan 21 '16 at 05:45

2 Answers2

1

you can add an execute(int a, int b) in B, but it won't override the execute(int a) method, it will overload it. Both method will be callable on an instance of B.

Roberto Attias
  • 1,883
  • 1
  • 11
  • 21
  • Yes it is fine if i use an instance of B, but in my case i use a instance of base class (A). – Viet Jan 21 '16 at 05:30
1

This would break the OO paradigm. The L in solid stands for Liskov substitution principle.

The principle applied for you example is that B should behave as A.

A better solution would be to injects those parameters via the constructor and have an execute without any parameters.

class A {
    int a;
    public A(int a){
        this.a = a;
    }
    public execute(){ // do something with a}
}

class B {
   int a;
   long b;
   boolean c;

    public B (int a, long b, boolean c) {
        this.a = a;
        this.b = b; 
        this.c = c;
    }

    public execute(){ // do something with a, b and c}

}
Glenner003
  • 1,450
  • 10
  • 20