构造函数有没有返回值?

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

    我告诉他说:构造函数没有返回值。 
    他举了个反例: 
      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)构造方法可以重载,以参数的个数,类型,或排列顺序区分。 
    我个人认为规定是没有返回的,但实际是隐式返回的类的对象。

  • 28
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值