3

I have the following problem with displaying an object as a string:

class Gast{

    String voorNaam, achterNaam;
    datum geboorteDatum;

    Gast(String vNaam, String aNaam, datum input){

        voorNaam = vNaam;
        achterNaam = aNaam;
        geboorteDatum = input;
    }

    public String toString(){

        return("Naam: " + voorNaam + " " + achterNaam + " " + geboorteDatum);
    }
}

here I implemented a way to represent this object in a string, however when I try to use that in this class:

class Kamer{

    boolean vrij;
    Gast gast;

    Kamer(){}

    public String toString(){

         if(vrij == true){

             return "De kamer is vrij!";
         }

         else{

             return gast;
         }
    }
}

I get the following error:

kamer.java:17: error: incompatible types: Gast cannot be converted to String
        return gast;

I gave a string representation of the object Gast in its class? Does the other class not inherit the representation I gave?

4
  • 4
    Because Gast is not a string. You have to call gast.toString(). Commented Nov 6, 2015 at 20:41
  • Thank you that fixed the error! and made me feel a bit stupid haha. Should i keep the question? Commented Nov 6, 2015 at 20:44
  • "Should i keep the question?" you have no choice since it has up-voted answer... Commented Nov 6, 2015 at 20:45
  • as you maybe realized i am pretty new on stack overflow community but thank you for the help! Commented Nov 6, 2015 at 20:50

1 Answer 1

7

Try:

return gast.toString();

Edit: Better yet, as suggested by @Andreas comment, use String.valueOf(gast) if there is a possibility gast can be null (or just check for null manually)

Sign up to request clarification or add additional context in comments.

3 Comments

Oh no, please no. Don't use "" + gast. If gast can be null, use String.valueOf(gast), not that bad construct, which compiles to new StringBuilder().append(gast).toString(). <shivers>
Followup: "" + gast results in: allocate StringBuilder, allocate char[16], allocate char[?] for actual length, copy text, allocate String, allocate char[?], copy text. 4-5 allocations and 2 copies of the text for each execution. All that overhead at runtime, just to save a few keystrokes. Sorry, pet peeve of mine.
@Andreas ok ok, i'll get rid of it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.