#Call System.out.print on object and get objects string field

14 messages · Page 1 of 1 (latest)

wise temple
#

I have a class

public class S {
  private String cont = "contents";
  
  public static void main(String[] args) {
    S myS = new S();
    System.out.println(myS);
  }
}

is there a way to make it so that the program outpus "contents"

golden vigilBOT
#

This post has been reserved for your question.

Hey @wise temple! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

sterile grail
#

System.out.println(cont);
you can make cont static here or create a getter and then call myS.getCont() or similar

harsh mica
#

either write a toString method in your class, or use myS.cont

wise temple
#

well a toString just return the String attribute when the object is passed to System.out.println?

harsh mica
#

if you tell it to

#

every object has a default toString() that shows the className and hashCode

#

if you override it, you can specify how to stringify your class

#

println will use that

wise temple
#

oh alright

#

thank you

golden vigilBOT
# wise temple thank you

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.