Java: printing or returning the name of a newly instantiated object in toString -


i typed on may have syntax errors, asked height, length, , name of object in tostring line. i'm getting height , length fine, don't know how name (rec1 , rec2) tostring.

public static void main (string[] args) {         rectangle rec1 = new rectangle();         rectangle rec2 = new rectangle();          system.out.println(rec1);         system.out.println(rec2); }   class rectangle {         private double height;         private double length;         ***private string name;***          public rectangle()         {              height = 8;              length = 6;              ***name = this.name***         }   

i tried adding string rectangle constructor, didn't know initialize string name to. left , set (we mutating height , length) of height , length out convenience.

        ***public string getname()         {              return name;         }          public void setname(string name)         {              this.name = name;         }***          public string tostring()         {            return (***name*** + height + " " + length);         } 

when used emphasized lines, name comes null. on right track?

to add name variable string returned tostring() method, concatenate rest of string returned.

either make private name field in rectangle class have, or make public.

@override public string tostring(){     return ("rectangle: name = " + name ", height = " + height + ", length = " + length); } 

this solve issue, far understand question.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -