构造函数有没有返回值?

阅读: 评论:0

构造函数有没有返回值?

构造函数有没有返回值?

  • 昨天面试,他问我:构造函数有没有返回值?

    我告诉他说:构造函数没有返回值。 
    他举了个反例: 
      String str = new String("content"); 

    new 的时候调用构造函数,返回给str; 

    再问:有没有方法确定知道构造函数有没有返回??

     

    这是 <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. 
    看最后一句话,构造方法是新创建的对象的实例变量缺省初始化以及显式初始化之后才执行的,也就是说在构造方法调用之前这个对象已经存在了,更谈不上你例子中的构造方法返回一个对象引用了。

     

    构造方法是一种特殊的方法,具有以下特点。 
    (1)构造方法的方法名必须与类名相同。 
    (2)构造方法没有返回类型,也不能定义为void,在方法名前面不声明方法类型。 
    (3)构造方法的主要作用是完成对象的初始化工作,它能够把定义对象时的参数传给对象的域。 
    (4)构造方法不能由编程人员调用,而要系统调用。 
    (5)一个类可以定义多个构造方法,如果在定义类时没有定义构造方法,则编译系统会自动插入一个无参数的默认构  造器,这个构造器不执行任何代码。 
    (6)构造方法可以重载,以参数的个数,类型,或排列顺序区分。 
    我个人认为规定是没有返回的,但实际是隐式返回的类的对象。

本文发布于:2024-02-02 03:59:29,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170681778141214.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:函数   返回值
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23