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

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

问题描述

据我所知,构造函数什么都不返回,甚至没有返回,

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

还有

return ;

在任何方法中都意味着返回 void .

inside any method means to return void .

所以在我的程序中

public class returnTest {

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

    }

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

我在打电话

return;

将返回 VOID ,但构造函数不应返回任何内容,程序编译得很好.

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

请解释.

推荐答案

return 在构造函数中只是在指定点跳出构造函数.如果在某些情况下不需要完全初始化类,则可以使用它.

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.

例如

// A real life example
class MyDate
{
    // Create a date structure from a day of the year (1..366)
    MyDate(int dayOfTheYear, int year)
    {
        if (dayOfTheYear < 1 || dayOfTheYear > 366)
        {
            mDateValid = false;
            return;
        }
        if (dayOfTheYear == 366 && !isLeapYear(year))
        {
            mDateValid = false;
            return;
        }
        // Continue converting dayOfTheYear to a dd/mm.
        // ...

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

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