I am new to OOP and I want to use functions from an extended class, but with different numbers of parameters, in JAVA - Android.
As far as I 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 the virtual Methods as follows
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 that it is not @Overriding
if i use parameters. I only need parameters from some sub classes, like Command1, Command10, but NOT from Command5, from witch I need to call Send and Parse without parameters.
Can you help me?
You may not change the parameter count, their types or order if you want to override a method in Java.
You definitely need a parameter here if some subtypes need one and polymorphism is required.
I recommend using a wrapper class. You could use the new Java 8 Optional type or Google Guavas Optional type. Alternatively, you could write one yourself if that provides additional benefit.
For Java 8 Optional 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 may also be of interest for you. The basic idea is to use an Object which may represent an empty parameter (similiar to an empty list rather than null).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.