关于构造方法

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

2.这是<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.

3.类的实例化其实就是分配一块内存空间,包括所有变量和方法,并且把整个这个内存空间的地址(引用)返回给str,而并不仅仅是返回构造函数构造的一些变量的值。

4.首先,类实例(也就是对象)只包含类的属性(成员变量),不包括方法的。方法是放在代码区的,虚函数表应该是类的公共数据,也不应该算在实例本身的空间内。其次,构造函数的功能,仅仅是对对象的内存空间作初始化,不负责空间分配的任务。

5.String str = new String("123");
这并不算返回值,你可以这样想:什么是返回值? 返回值,可以自己任意定义返回的类型,可以自己任意定义返回的大小甚至是null. 但是new就不可以。new 会创建一个对象,并且返回对象的地址,也可以认为是引用。这不是返回值,而是new关键字本来的功能

6.new 运算符返回的对象引用或者指针
new负责在堆上分配对象所需的内存空间
构造函数负责在此位置构造对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值