Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

java - how to explain return statement within constructor?

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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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.
        // ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...