java中构造函数返回值的用途是什么以及如何访问此值?(What is the use of constructor return value in java and how to access th

编程入门 行业动态 更新时间:2024-10-24 11:21:42
java中构造函数返回值的用途是什么以及如何访问此值?(What is the use of constructor return value in java and how to access this value?)

由于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.

更多推荐

本文发布于:2023-08-03 08:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   用途   java   return

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!