Java "Virtual" method with variable number of parameters

I am new to OOP and I want to use functions from an extended class, but with different number of parameters, in JAVA - Android.

As far as I can remember in C #, I can do the following:

Main class

    class Command {
     protected int NrTokens
     protected String cmd
     protected String[] AnswerTokens

     Command(String[] Tokens) { 
        AnswerTokens = Tokens   
    }
     virtual int Parse()
     virtual int Send()
}

      

And use virtual methods like this

class Command1 : Command{
 protected int NrTokens=2;
 protected String cmd="abc";
 protected String AnswerTokens;
//

class ComandPing():Command(AnswerTokens);


public void Parse(){
if (AnswerTokens.size != NrTokens) 
    throw exception
//show on screen the status
}

Send() {
    //todo
}
}

      

I tried in Java like this

abstract class Command {
    protected int NrTokens;
    protected String cmd;
    protected String[] AnswerTokens;


    public void SetAnswerTokens(String Tokens[]){
        AnswerTokens = Tokens;
    }


    abstract void Parse();
    abstract void Send();



}

      

AND

public class Command1 extends Command {

    protected int NrTokens=2;
    protected String cmd="PING";
    protected String AnswerTokens;

    public Command1(String Tokens[]){

    }

    @Override
    void Parse(String b){
        if (AnswerTokens.length()!= NrTokens)
        {

        }

    }

    @Override
    void Send(int a) {

    }

      

The problem is I am not using parameters @Overriding

. I only need parameters from some subclasses like Command1, Command10, but NOT from Command5, from witch I need to call Send and Parse without parameters.

Can you help me?

+3


source to share


1 answer


You cannot change the number of parameters, their types or their order if you want to override a method in Java.

You definitely need a parameter here if any subtypes are needed and polymorphism is required.

I recommend using the wrapper class. You can use the new Java 8 or Google Guavas optional type. Alternatively, you can write it yourself if it provides additional benefit.

For Java 8 For more see https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html



For Guava Optional see https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained

The null object pattern might also be of interest to you. The basic idea is to use an object that can represent an empty parameter (similar to an empty list, not empty).

See: http://en.wikipedia.org/wiki/Null_Object_pattern

0


source







All Articles