FAQ: Learn Java: Methods - The toString() Method

Yes, that’s an important information that was missing in this lesson. But this is a kinda recurring issue. I have the feeling sometimes things are not really told on really basic level but just “Do this and that will happen, isn’t this nice?” instead of “If you do this then that will happen because of this reason.”
For example for me it wasn’t clear that you can have only one constructor per class and that the constructor has to have the name of the root class which has to have the name of the file. I was wondering how you would assign methods to the object.
The concept of 1 file = 1 class = 1 object and everything within this file/class is part of this object wasn’t that clear from the get-go. Maybe I missed this somewhere, but I felt like you were just getting thrown into it and the explanation was added later.

You just summarized why Java is difficult first programming language to learn. There simply is a lot needed to get started

finding a balance between not overwhelming new learners (by cramming too much info into too few lessons) and missing out crucial information is very difficult.

2 Likes

Yeah, I totally get that!
In that case I suggest to make a note in the beginning (“Introduction to Classes”, first exercise).

I mean, OOP is not that difficult of a concept, what made me stumble in java was just this fact that 1 file/class = 1 object. Javascript for example handles this a little different, you can have multiple constructors/objects in one single file.

I remember when I first about OOP, I didn’t find it that easy. Combined with inheritance, method overwrite, constructors, controlling access to members of a class and building a good design, very difficult

but still just one constructor per class. And javascript classes. And JavaScript classes are also complicated, given how javascript deals with object and inheritance:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

Also, you raise an interesting point. Yes, we can have multiple objects within a single file in JS. Question: Do we want this? Structuring your code is very important, and Java enforces this where Javascript doesn’t

Trust me, you don’t want a file with 5000 lines of code and many objects. That is just a nightmare (one i haven’t ran into thankfully, hopefully it stays that way :slight_smile: )

anyway, we are getting a bit off-topic even though its an interesting discussion

Well, yeah. I mean, the concept itself is not that difficult, but to execute on it correctly is a challenge. Especially when you talk about root classes and how they may impact you inherited classes and how they affect them.

Hmm…while this is true I do like the other concept too. It allows you to approach it in a different manner. You might do a file per functioning sub-part of your program. While this will result in bigger files it may help in structuring your code better across multiple files. All objects needed for a functioning sub-part could be in one file instead of spread over multiple files.

And yes, Javascript object handing is interesting, I’m currently experimenting with Node-Red to get some stuff running and it has thrown a few rocks into my path.

2 Likes

I don’t see where the 'toString() Method is called.

Its literally stated in the exercise:

When we define a toString() method for a class, we can return a String that will print when we print the object

with example:

class Car {

    String color;

    public Car(String carColor) {
        color = carColor;
    }

    public static void main(String[] args){
        Car myCar = new Car("red");
        System.out.println(myCar);
    }

   public String toString(){
       return "This is a " + color + " car!";
   }
}

sure, there is no direct call, Java does this call under the hood. But the explanation and example should suffice.

Is the ‘under the hood’ only applicable to ‘toString()’ or are there a few others or too many to mention ?

Given the million of man hours that went into teaching a piece of rock to think, its safe to assume there is a lot happening under the hood.

1 Like

It seems like you may have put cookieShoo instead of cookieShop
or on the second System.out.println i seems like you may have used a colon instead of a semicolon

you probably have already figured it out or used the see answer code option but just in case i thought i would try

This comment thread was so helpful I didn’t understand that you could only have one constructor per class i was so confused about how it would work if you had multiple constructors but now i know that there can only be one per class

This helped so much
Thanks

You can have multiple constructors for a class in Java. This is called constructor overloading and it’s similar to method overloading.

The post you replied to was about multiple constructors in JavaScript, which is not allowed. Note that Java and JavaScript are two different languages.

ik that java and js are different languages but they said

and then they say

Didn’t they just say that java enforces this but JS doesn’t? and if java doesnt enforce it then having two constructors would be wierd bc if i printed a car for example then it would make no sense

This is the full part of the reply. It’s a bit ambiguous but I believe it’s referring to having multiple objects in a single file rather than multiple constructors. To clarify, you can have multiple objects in both Java and JS, but multiple constructors only in Java. Note that objects are different from constructors.


You can have multiple constructors in Java; they have to take in different arguments so the compiler knows which constructor should be used. The following article explains this.

You refer to “printing a car.” If you have written some code and have specific questions about it and its constructors, you can post it here (please format it according to this post).

Sorry i wasnt that specific here i will try to be more specific: I was confused but from that article you referenced I think i understand now, so is it that you can have multiple constructors but they have to have the same name as the class? the thing i was confused about is how toString would make sense if you had multiple constructors. And with constructor overloading how would toString make sense? because they have to have different parameters so if i made to toString according to the first cunstructor and then printed the sencond one how would it work for example:

class Student {

    private String name;

    private int id;

    //example of no-argument constructor
    public Student() {
        System.out.println("no-argument constructor called !");
    }

    //example parameterized constructor (1 param)
    public Student(String name) {
        this.name = name;
        System.out.println("constructor with one argument called !");
    }
//example parameterized constructor (2 params)
public Student(String name, int id) {
    this.name = name;
    this.id = id;
    System.out.println("constructor with two arguments called !");
}

}
(That was from the article) if I made a toString method I don’t understand how you could get it to make sense because all of the constructors have different parameters so wouldn’t toString only make sense for objects coming from a specific constructor?

I’m just confused about how toString() works with multiple constructors

Yes! Constructors always have to have the same name as the class regardless of whether there is one or multiple constructors.

There are multiple ways you could go about this. If you look at the example, the variables name and id are declared at the beginning of the class. Even if they aren’t assigned values because either the no-argument constructor or 1-argument constructor was called, these variables still exist because you have declared them. They will have default values based on their data types (e.g. null for strings, 0 for ints). Because these variables exist and have value (even if they are the default values), you can build a toString method that will use all of these variables. Then, the default values will simply be used for the variables that were not assigned values in the constructor. The following resource may be helpful as well.

Thank you! that answered my question! this is very helpful, but i would like one clarification, do constructor methods have to have the same name as the class?

1 Like

victoria already covered this:

but this is Java specific, this will not apply to all other programming language you might learn

1 Like

public String toString(){

  return "This store sells "+ productType +"at a " + price + " of " + price + ".";

}