Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can objects inherit string representations?

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?

like image 907
Arkin Zoodsma Avatar asked Dec 30 '25 01:12

Arkin Zoodsma


1 Answers

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)

like image 50
kcraigie Avatar answered Dec 31 '25 18:12

kcraigie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!