java 中 return 是什么用途,要个详细的。

来源:百度知道 编辑:UC知道 时间:2024/06/10 22:04:14
class Text
{
int a;
int b;
int add()
{
System.out.println(a+b);
return a+b;
}
int sub()
{
System.out.println(a-b);
return a-b;
}
}
class Text1 extends Text
{
int add()
{
System.out.println(a);
return a;
}
int sub()
{
System.out.println(b);
return b;
}
long sub(long a)
{
System.out.println(a);
returna;
}
}
class Text2
{
public static void main(String args[])
{
Text1 aa=new Text1();
aa.a=4;
aa.b=5;
aa.sub();
aa.add();
aa.sub(4);
}
}
这些是一本java 自学书上的代码。
说是运行结果是5, 4, 4,
我想知道,return是什么意思。
要个详细的说明。谢谢了。
小弟新人,没有多少分。
大大们不要嫌弃。

return 一句话简单来说就是返回的意思
比如你的int add(){ System.out.println(a+b); return a+b; }
意思就是说你先将a和b打印出来了,然后将它们的和返回。
如果你用一个int类型的变量接收这个返回的“和”可以这样写
int c;
c=add();
这样就是表示
b=a+b;的意思了

众所周知,return 用在有返回类型的函数中,但是有返回值的函数一定要有return吗?return都可以用在函数的哪些地方呢?这是本文需要讨论的问题。

---------------------------------------------------------------------
例一:

class test {
public String test() {
if(true){
return "";
}
else{
return "";
}
}
}
上面这样即可通过编译,但是下面这两个例子却不能通过编译:

(一)
class test {
public String test() {
if(true){
return "";
}
}
}

(二)
class test {
public String test() {
if(isTrue()){
return "";
}
else if(!isTrue()){//两个if里的判断包括了所有的可能性,但是还是编译期error
return