0

How do I make a method that does not require an objects, but if there is one it would use it!

Like this

void cls(String source){
        if(source.isEmpty()){
            source = "Unknown source";
        }
        output.setText("Screen cleared from " + source);
    }

And later when I call this I could do

cls();

but it throws an error because it needs a string

cls("string");

but I want for both to work!

donemanuel
  • 49
  • 1
  • 9
  • 6
    overload your `cls` method – Luiggi Mendoza Jul 10 '13 at 14:36
  • Note, you may want to give your method distinct meaningful names rather than overloading. – Tom Hawtin - tackline Jul 10 '13 at 14:41
  • @TomHawtin-tackline not neccesarily, it looks like common cls command to clear a screen (also noted in the output.setText("___") message). – Luiggi Mendoza Jul 10 '13 at 14:42
  • 3
    To last editor: adding *How to overload* in title would make the question to be closed. In its current state, it shows lack of knowledge from OP about how to accomplish this task. – Luiggi Mendoza Jul 10 '13 at 14:45
  • 3
    [This question](http://stackoverflow.com/questions/965690/java-optional-parameters) is related and might help OP understand Java's limitations as far as optional arguments within a single method definition. – ajp15243 Jul 10 '13 at 14:50

2 Answers2

7

You use two methods with the same name but different signatures (that's called overloading):

void cls() {
    // ???
}

void cls(String source){
    if(source.isEmpty()){
        source = "Unknown source";
    }
    output.setText("Screen cleared from " + source);
}

or varargs:

void cls(String... sources){
    if (sources.length > 0) {
        // ???
    }
}
ajp15243
  • 7,704
  • 1
  • 32
  • 38
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • This works, but what if I have void `cls(String source, boolean isAllowed){}` – donemanuel Jul 10 '13 at 14:42
  • I want both string source and boolean isAllowed to be unnecessary! – donemanuel Jul 10 '13 at 14:43
  • 4
    @donemanuel You can "chain" overloaded methods together for as many arguments as you want. Just have your no-args method call the full version, with default arguments. `void cls() { cls("Unknown source", false); }` or whatever else you want for your default arguments. – Henry Keiter Jul 10 '13 at 14:44
0

you can create two methods. something like this:

void cls(String source) {...}

void cls() {
    return cls("Unknown source");
}

now you can call cls with or without the String parameter

Vegard
  • 1,802
  • 2
  • 21
  • 34