据我所知,构造函数什么也没有返回,甚至没有返回,
以及
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,但构造函数不应返回任何内容, 该程序编译得很好。
请解释。
答案 0 :(得分:21)
return
只是跳出指定点的构造函数。如果在某些情况下不需要完全初始化类,可以使用它。
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.
// ...
答案 1 :(得分:2)
返回 语句后的语句将无法访问。如果return语句是最后一个,那么在构造函数中定义是没有用的,但编译器仍然没有抱怨。它汇编得很好。
如果您在 if 条件的基础上在构造函数中进行一些初始化,您可能希望初始化数据库连接(如果可用)并返回其他您想要的从本地磁盘读取数据以用于临时目的。
public class CheckDataAvailability
{
Connection con =SomeDeligatorClass.getConnection();
public CheckDataAvailability() //this is constructor
{
if(conn!=null)
{
//do some database connection stuff and retrieve values;
return; // after this following code will not be executed.
}
FileReader fr; // code further from here will not be executed if above 'if' condition is true, because there is return statement at the end of above 'if' block.
}
}
答案 2 :(得分:2)
return
可用于立即离开构造函数。一个用例似乎是创建半初始化对象。
人们可以争论这是否是一个好主意。问题恕我直言,结果对象很难使用,因为它们没有任何你可以依赖的不变量。
在我到目前为止看到的所有在构造函数中使用return
的示例中,代码都存在问题。通常构造函数太大并且包含太多的业务逻辑,因此很难进行测试。
我见过的另一种模式在构造函数中实现了控制器逻辑。如果需要重定向,则构造函数存储重定向并返回调用。除了这些构造函数也难以测试之外,主要的问题是无论何时必须使用这样的对象,你都必须悲观地认为它没有完全初始化。
更好地保留构造函数中的所有逻辑,并以完全初始化的小对象为目标。然后你很少(如果有的话)需要在构造函数中调用return
。
答案 3 :(得分:1)
使用void
返回类型声明的方法以及构造函数只返回任何内容。这就是为什么你可以在其中省略return
语句的原因。为构造函数指定void
返回类型的原因是为了区分构造函数和具有相同名称的方法:
public class A
{
public A () // This is constructor
{
}
public void A () // This is method
{
}
}
答案 4 :(得分:1)
在这种情况下,return
的行为与break
类似。它结束初始化。想象一下有int var
的班级。您已通过int[] values
并希望将var
初始化为int
中存储的任何正values
(否则为var = 0
)。然后,您可以使用return
。
public class MyClass{
int var;
public MyClass(int[] values){
for(int i : values){
if(i > 0){
var = i;
return;
}
}
}
//other methods
}
答案 5 :(得分:0)
public class Demo{
Demo(){
System.out.println("hello");
return;
}
}
class Student{
public static void main(String args[]){
Demo d=new Demo();
}
}
//output will be -----------"hello"
public class Demo{
Demo(){
return;
System.out.println("hello");
}
}
class Student{
public static void main(String args[]){
Demo d=new Demo();
}
}
//it will throw Error