简体   繁体   中英

replacing system.out.println(class) in java

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?

Change your Window to

public void println(Object obj)
{
    textArea.append(obj +"\n"); 
}

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()); 
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM