I’m trying to figure out how java classes work.
When I create a StringBuilder:
StringBuilder testString = new StringBuilder("Hello World!);
If I want to, say, get the value that testSting holds a reference to, I can simply call it like: System.out.println(testString);
This is cool behavior, but I’m unsure how to replicate it in classes that I make.
For instance, if I were to try and re-implement my own version of StringBuilder, the approach I would take (as a beginner), would be this:
class MyBuilder {
char[] string;
public MyBuilder(String s) {
string = new char[s.length()];
string = s.toCharArray();
}
So, to make the string an array I had to store it in a data field of the class. But then, to access this in my code, I can’t print it by simply calling the variable name. I would have to use .property syntax. Thus, to duplicate the above example, I would have to type System.out.println(testString.value); Which isn’t nearly as pretty.
How do you make a class such that it behaves like String or StringBuilder and returns its value without manually accessing the data fields?
Implement a
toStringmethod.toStringis a method onObject, so every java object inherits one. The default implementation that you inherit is only useful for getting the class type, and for distinguishing one object from another; the format is: ClassName@HashCode. There are no details unique to your implementation.In your own classes, to get the description that you want you’ll need to override the
toStringmethod, so that in contexts where aStringis expected, e.g. when you callSystem.out.println(myObject.toString());, your own format is used.It’s often a good idea to do this, for a more readable description of your object. You can always call
super.toStringto include the output from the default – ClassName@HashCode – in your own output.