Java构造函数是否返回Object引用? [英] Does a Java constructor return the Object reference?

查看:126
本文介绍了Java构造函数是否返回Object引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java的构造函数不能有任何类型,有趣的是,它甚至不能是 void 。对此的逻辑解释是构造函数返回初始化对象的引用。

I know Java's constructors can't have any type and interestingly it cannot even be void. A logical explanation for that would be that a constructor returns the initialized object's reference.

MyClass myObject = new MyClass();

myClass 的构造函数现在将返回实例化对象引用并将其保存在对象变量 MyObject 之后,这就是构造函数无法具有返回类型的原因。

The constructor of myClass will now return the object reference after instantiating it and save it in the object variable MyObject and that's why the constructor can't have a return type.

是吗?有人可以确认吗?

Is that right? Could someone confirm this?

推荐答案

不,实际上,构造函数已编译到类文件名为< init> void 返回类型。您可以看到这些< init>" 堆栈跟踪中的调用。表达式 new Type()被编译为一条指令 new 仅创建 Type 和其他方法调用( invokespecial )到在 Type 中声明的构造函数之一。

No, actually, the constructors are compiled into the class file like methods having the name <init> and a void return type. You can see these "<init>" invocations in stack traces. The expression new Type() is compiled as an instruction new which just creates the instance of Type and an additional method invokation (invokespecial) to one of the constructors declared in Type.

验证者将确保立即在新创建的实例上立即调用这种特殊方法,并确保在其他任何使用该对象之前调用该特殊方法。

The verifier will ensure that such a special method is invoked at exactly once on a newly created instance and that it is called before any other use of the object.

从Java语言的角度来看,让构造函数没有返回类型只是一个编程语言设计的决定。毕竟, new Type(…) 一个表达式,其结果为新创建的 Type ,您将无法从具有该编程语言构造的构造函数获得返回值。此外,如果添加返回类型,则Java将无条件地假定它是一种方法,即使它与该类具有相同的名称。

It’s just a programming language design decision to let constructors have no return type from the Java language point of view. After all, new Type(…) is an expression that evaluates to the newly created instance of Type and you can’t get a return value from the constructor with that programming language construct. Further, if you add a return type, Java will unconditionally assume that it is a method, even if it has the same name as the class.

这就是它的简单定义方式 :(它使解析类


ConstructorDeclarator中的SimpleTypeName必须是包含构造函数声明的类的简单名称,否则会发生编译时错误。

The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration, or a compile-time error occurs.

在所有其他方面,构造函数声明看起来就像没有结果的方法声明(第8.4.5节)。

In all other respects, a constructor declaration looks just like a method declaration that has no result (§8.4.5).

这篇关于Java构造函数是否返回Object引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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