由于JDK 8允许返回类型的构造函数,并且还允许从构造函数返回一个值,因此它的用途是什么? 如何在下面的程序中访问构造函数的返回值?
public class ConstructorReturn { int ConstructorReturn() { return 10; } public static void main(String... args) { ConstructorReturn constructorReturn = new ConstructorReturn(); } }As JDK 8 allows return type of constructor and also allows to return a value from constructor so what is the use of it? How to access return value of constructor in below program?
public class ConstructorReturn { int ConstructorReturn() { return 10; } public static void main(String... args) { ConstructorReturn constructorReturn = new ConstructorReturn(); } }最满意答案
int ConstructorReturn() { return 10; }那不是构造函数。 这是一个与类同名的常规方法。 构造函数没有返回值。
构造函数永远不会有返回值(甚至无效):
ConstructorReturn() { }你的ConstructorReturn constructorReturn=new ConstructorReturn(); line不会调用您的ConstructorReturn方法。 它调用由编译器生成的默认无参数构造函数,因为您的类没有任何显式构造函数。
int ConstructorReturn() { return 10; }That's not a constructor. It's a regular method having the same name as the class. A constructor has no return value.
A constructor will never have a return value (not even void) :
ConstructorReturn() { }Your ConstructorReturn constructorReturn=new ConstructorReturn(); line doesn't invoke your ConstructorReturn method. It invokes the a default parameterless constructor that was generated by the compiler, since your class didn't have any explicit constructors.
更多推荐
发布评论