1
// set date of birth
    public void setDOB(int day, int month, int year)
    {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    // get date of birth
    public int getDOB()
    {
        return day;
        return month;
        return year;
    }

Why do I get an error when I try to return these three values? I thought I was able to do something like this in order to save some space by not writing each set/get method for day, month, and year.

Also, I only seem to get an error with return month;, meaning it's the only one that eclipse has highlighted to tell me to delete it.

Onikouzou
  • 37
  • 7

3 Answers3

3

You cannot return multiple values with return statements same time. When the first return statement executes the remaining two statements become unreachable.

Possible solutions

1) Return an array

2) Return a list of int's

3) Or construct an object and return it.

When you wrote getDOB() that should be a Date object, not an int. It seems you need to return a Date object there.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You cant. The first return statement will end the method and return control to the caller. Further returns will never be reached. You can only return a single value from any method, and you specified the return type as int.

Daniel Langdon
  • 5,899
  • 4
  • 28
  • 48
  • So I'm going to have to just create set/get methods for each? – Onikouzou Sep 24 '15 at 02:28
  • @Onikouzou yes you have to create separate set/get methods for each. if you are using eclipse, [this](http://stackoverflow.com/q/7221691/2431281) could help you – Keale Sep 24 '15 at 02:30
  • @Onikouzou to be honest, this particular case I would recommend you to use an existing Date class rather than roll your own. Google for JodaTime. – Daniel Langdon Sep 24 '15 at 03:02
1

Why do I get an error when I try to return these three values?

Return type int means your method will return int only and once return statement executed your other code becomes dead after the return statement because after return number; control directly goes to the caller of the method.

You should return Date in your case, as it's all about Date of birth.

Moreover, you can have three different getter methods instead (not recommended in your case).

public int getDay(){ return day;}
public int getMonth(){ return month;}
public int getYear(){ return year;}
akash
  • 22,664
  • 11
  • 59
  • 87