如何解释构造函数中的return语句? [英] how to explain return statement within constructor?

查看:144
本文介绍了如何解释构造函数中的return语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,构造函数返回无,甚至无void,



以及

  return;任何方法中的



意味着返回void。



所以在我的程序

  public class returnTest {

public static void main args){
returnTest obj = new returnTest();
System.out.println(here1);

}

public returnTest()
{
System.out.println(here2);
return;
}
}

我正在呼叫

  return; 

这将返回VOID,但是构造函数不应该返回任何东西,
程序编译正确。



请解释。

解决方案

return 在构造函数中只是跳出构造函数的指定点。



例如



<$ p如果您在某些情况下不需要完全初始化类, $ p> //一个非常有用的例子...
class Demo
{
protected int id = 0;
protected int count = 0;
public Demo(int id,int count)
{
this.id = id;
this.count = count;
if(this.count< = 0){
return;
}
// count> 0,做一些有意义的事情


as far as i know , the constructor return nothing , not even void ,

and also

return ;

inside any method means to return void .

so in my program

public class returnTest {

    public static void main(String[] args) {
        returnTest obj = new returnTest();
        System.out.println("here1");

    }

    public returnTest () 
    {
        System.out.println("here2");
        return ;
    }
    }

i am calling

return;

which will be returning VOID , but constructor is not supposed to return anything , the program compiles just fine .

please explain .

解决方案

return in a constructor just jumps out of the constructor at the specified point. You might use it if you don't need to fully initialize the class in some circumstances.

e.g.

// A very contrived example...
class Demo
{
    protected int id = 0;
    protected int count = 0;
    public Demo(int id, int count)
    {
        this.id = id;
        this.count = count;
        if (this.count <= 0) {
            return;
        }
        // count > 0, do something meaningful

这篇关于如何解释构造函数中的return语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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