JAVA中构造函数有没有返回值_【面试题】构造函数有没有返回值

构造函数在JAVA中没有返回值,它们用于初始化新创建的对象。new关键字负责分配内存和初始化,而构造函数执行对象的定制初始化。官方文档确认构造方法不具备返回类型,其行为在方法声明中独一无二。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

曾经遇到一个面试题——构造函数有没有返回值?今天调查一番后,给出确切的答案:构造函数没有返回值。

我们使用构造函数构造一个String字符串str:

String str = new String("abc");

这里的new 是调用构造函数,在堆里动态创建一个String对象,并让str指向这个对象。实际上赋值是因为new关键字,而不是()在起作用。

从语法上讲,构造函数不允许有返回值,就算是 void 也不行。可以确定构造函数没有返回值吗?

这是 上的说法:

For purposes other than simple initialization, classes can have constructors. Constructors are blocks of statements that can be used to initialize an object before the reference to the object is returned by new. Constructors have the same name as the class they initialize. Like methods, they take zero or more arguments, but constructors are not methods and thus have no return type. Arguments, if any, are provided between the parentheses that follow the type name when the object is created with new. Constructors are invoked after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializers a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值