构造函数有没有返回值

疑问在于如下的代码:

String str = new String(content);

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

从语法上讲,构造函数不允许有返回值,就算是 void 也不行。

这里的new 是调用构造函数,在堆里分配了一个String对象,并让str指向这个对象。实际上是那个 new 在起作用,而不是()在起作用。

下面是因为原版说明,有兴趣的自己看吧

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.

下面是构造方法的一些特点总结

(1)构造方法的方法名必须与类名相同。

(2)构造方法没有返回类型,也不能定义为void,在方法名前面不声明方法类型。

(3)构造方法的主要作用是完成对象的初始化工作,它能够把定义对象时的参数传给对象的域。

(4)构造方法不能由编程人员调用,而要系统调用。

(5)一个类可以定义多个构造方法,如果在定义类时没有定义构造方法,则编译系统会自动插入一个无参数的默认构 造器,这个构造器不执行任何代码。

(6)构造方法可以重载,以参数的个数,类型,或排列顺序区分。

当然

public Long String(){ }

这个算一个普通的方法,虽然和类重名,但却是合法的普通方法,而不是构造方法了。

如下的类可以正常编译并运行,结果正确。请注意构造方法里面的return;

public class T {

public T() {

return; // 请注意这里的return哦,这是合法的语句

}

public String T() {

return 特殊的方法,和类名相同;

}

public static void main(String[] args) {

System.out.println(new T().T());

}

}

从另一个角度看,正是因为构造函数没有返回值才需要这么写:

String str = new String(content);

否则,如果有返回值,应该如下写:

String str = String(content);

当然了,那个String是一个普通的方法,不再是构造方法了。原因看前面的例子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值