Reputation: 21
I've got some classes which include toString functions which work very well as:
snipped of declaration:
public String toString() {
return "Port info: "+myPort.variable;
}
snipped of main():
Port myPort;
myPort.fillInfo();
system.out.println(myPort);
output:
"Port info: 123"
I'm trying to replace all my system.out.println(myPort) calls with myWindow.println(myPort) calls where myWindow contains:
public void println(String toPrint)
{
textArea.append(toPrint+"\n"); //or insert
}
However, I'm getting:
The method println(String) in the type window is not applicable for the arguments (Port)
In other words, my declaration is expecting the String type, and I'm trying to pass it the Port type.
Somehow, system.out.println() will take any class that's got a toString() declared.
How does system.out.println take any class and print it out, and run its toString() method if it exists? And, more to the point, how can I replicate this functionality for my own println() function?
Upvotes: 2
Views: 3147
Reputation: 201439
First, please don't use \n
as a line separator (it isn't portable). In addition to overloading println(Object)
, you could make your method generic. Something like
public <T> void println(T obj)
{
textArea.append(String.format("%s%n", obj));
}
or
public void println(Object obj)
{
textArea.append(String.format("%s%n", obj));
}
or
public void println(Object obj)
{
textArea.append((obj == null ? "null" : obj.toString())
+ System.lineSeparator());
}
Upvotes: 2
Reputation: 1
The problem is that System.out has a method to print to console an object as it contains for all primitive data types. The thing about this is that as all methods have the same name and just change the data type of the parameter you want to print, you think you can pass an object by a string and is not. The method .println() automatically takes which passes an object. Within this method .println() he takes the object that you indicated by parameters and calls his method .toString() to obtain the string representation of the object and printed on the console.
If you want to print any type of object you must declare your parameter as object type and invoke the method .toString() from the object and print that information.
Upvotes: 0
Reputation: 44834
Change your Window
to
public void println(Object obj)
{
textArea.append(obj +"\n");
}
Upvotes: 3
Reputation: 223003
PrintStream.println
has an overload that takes an Object
argument. You can make your println
do the same.
Upvotes: 2