Java 中“void 方法”和“返回类型方法”的主要区别是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35410595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the main difference between 'void method' and 'return type method' in Java?
提问by Waseem
public void printString(String str) {
System.out.println(str);
}
public String stringMethod(String str) {
return str;
}
I have write the code with two methods, one is void (print the string message) and second is return the String. So those two are the almost same, the difference is just return statement in String method. Can anybody explain those two with real life examples?
我用两种方法编写了代码,一种是 void(打印字符串消息),第二种是返回字符串。所以这两个几乎是一样的,区别只是String方法中的return语句。谁能用现实生活中的例子来解释这两个?
回答by f1v3
I shall try to explain the best I can:
我将尽力解释:
public void printString(String str) {
System.out.println(str);
}
The "void" return type means that this method doesn't have a return type. It actually doesn't need one because you "print" your String onto the System's output stream. In an application, this approach may be used to print runtime specific messages on the console for example.
“void”返回类型意味着此方法没有返回类型。它实际上不需要一个,因为您将字符串“打印”到系统的输出流上。例如,在应用程序中,此方法可用于在控制台上打印运行时特定消息。
public String stringMethod(String str) {
return str;
}
This other method on the other hand, returns a String. This means that you can use the returned value in your code for further processing. I guess good examples of such methods are "getters". These methods return field values of an object.
另一方面,另一个方法返回一个字符串。这意味着您可以在代码中使用返回值进行进一步处理。我想这种方法的好例子是“getter”。这些方法返回对象的字段值。
For example take the object Person:
以对象 Person 为例:
import java.lang.String;
public class Person {
private String name;
private String surename;
private int age;
public Person(String name, String surename, int age) {
this.name = name;
this.surename = surename;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Person: " + surename + ", " + name + ". Age: " + age;
}
public void printPerson() {
System.out.println(this.toString());
}
}
Here you can see that the printPerson() uses the toString() method's returned value to print the result on the output stream.
在这里您可以看到,printPerson() 使用 toString() 方法的返回值在输出流上打印结果。