Java中'void方法'和'返回类型方法'的主要区别是什么? [英] What is the main difference between 'void method' and 'return type method' in Java?

查看:938
本文介绍了Java中'void方法'和'返回类型方法'的主要区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void printString(String str) {
    System.out.println(str);
}

public String stringMethod(String str) {
    return str;
}

我用两种方法编写代码,一种是void(打印字符串)消息),第二个是返回String。所以这两者几乎相同,区别在于String方法中的return语句。任何人都可以用现实生活中的例子来解释这两个吗?

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?

推荐答案

我会尽力解释一下:

public void printString(String str) {
     System.out.println(str);
}

void返回类型表示此方法没有返回类型。它实际上不需要一个,因为您将String打印到系统的输出流上。
在应用程序中,此方法可用于在控制台上打印特定于运行时的消息。

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.

public String stringMethod(String str) {
    return str;
}

另一方面,这另一种方法返回一个String。这意味着您可以使用代码中的返回值进行进一步处理。
我想这些方法的好例子是getters。这些方法返回对象的字段值。

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.

例如,取对象Person:

For example take the object 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());
    }
}

在这里你可以看到printPerson()使用了toString()方法的返回值,用于在输出流上打印结果。

Here you can see that the printPerson() uses the toString() method's returned value to print the result on the output stream.

这篇关于Java中'void方法'和'返回类型方法'的主要区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆