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

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

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

    String str = new String("abc"); 

  这里的new 是调用构造函数,在堆里动态创建一个String对象,并让str指向这个对象。实际上赋值是因为new关键字,而不是()在起作用。
  从语法上讲,构造函数不允许有返回值,就算是 void 也不行。可以确定构造函数没有返回值吗?

  这是 <The Java Programming Language>上的说法:
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 are executed.

We create the object sun refers to using new. The new construct is by far the most common way to create objects (we cover the other ways in Chapter 16). When you create an object with new, you specify the type of object you want to create and any arguments for its construction. The runtime system allocates enough space to store the fields of the object and initializes it in ways you will soon see. When initialization is complete, the runtime system returns a reference to the new object.
  看最后一句话,构造方法是新创建的对象的实例变量缺省初始化以及显式初始化之后才执行的,也就是说在构造方法调用之前这个对象已经存在了,更谈不上构造方法String("abc")返回一个对象引用了。
  对于类似这样的Java基础问题,最好的方法当然是去官方的资料寻找答案。于是情不自禁地翻阅了Java 11语言规范的文档,在章节 8.8 Constructor Declarations 中,关于构造方法的定义有以下说明:
In all other respects, a constructor declaration looks just like a method declaration that has no result (§8.4.5).
  中文意思大概如下:除了没有返回值,在所有其它方面,定义一个构造器非常像定义一个方法。这从定义的角度告诉我们,构造器没有返回值;同时也说明构造器不是方法,二者的唯一区别是是否有返回值。

  构造方法就像一种特殊的方法,具有以下特点:

  1. 构造方法的方法名必须与类名相同。
  2. 构造方法没有返回类型,也不能定义为void,即在方法名前面不声明方法类型。
  3. 构造方法的主要作用是完成对象的初始化工作,它能够把定义对象时的参数传给对象的域。
  4. 构造方法不能由编程人员调用,而要由系统调用。
  5. 一个类可以定义多个构造方法,如果在定义类时没有定义构造方法,则编译系统会自动插入一个无参数的默认构造器,这个构造器不执行任何代码。
  6. 构造方法可以重载,以参数的个数、类型或者排列顺序区分。
原文地址:https://www.cnblogs.com/east7/p/13939069.html