曾经遇到一个面试题——构造函数有没有返回值?今天调查一番后,给出确切的答案:构造函数没有返回值。
我们使用构造函数构造一个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