构造方法(构造器 constructor)
构造器勇于对象的初始化,而不是创建对象
创建对象的四步
- 分配对象空间,并将对象成员变量初始化为0或空
- 执行属性值的显示初始化
- 执行构造方法
- 返回对象的地址给相关的变量
声明格式:
[修饰符] 类名 (形参){
//语句;
}
构造器的4个特点
- 构造器通过new关键字调用!!
- 构造器是没有返回值的,同时也不能定义返回值类型(返回值的类型是本类的类型),不能在构造器里使用return返回某个值
- 构造器的方法名必须和类名一致
- 如果没有定义构造器,那么编译器就会自动定义一个无参的构造方法。
课后作业
/**
* 定义一个“点”(Point)类用来表示二维空间中的点(有两个坐标)。要求如下:
* 可以生成具有特定坐标的点对象。
* 提供可以计算该“点”距另外一点距离的方法。
*/
package com.zxp;
public class Point {
double x,y;
public Point(double _x, double _y) {
this.x = _x;
this.y = _y;
}
public double getDistence(Point p){
double d = Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
return d;
}
public static void main(String[] args) {
Point p1 = new Point(3.0,4.0);
Point o = new Point(0.0,0.0);
System.out.println(p1.getDistence(o));
}
}
构造方法的重载
构造方法也是方法。与普通方法一样,也可以重载
例如:利用构造方法创建不同的用户对象
/**
* 测试构造方法的重载
*/
package com.zxp;
public class TestUser {
int id;
String name;
int age;
char sex;
public TestUser(int id, String name) {
this.id = id;
this.name = name;
}
public TestUser(int id, String name, char sex){
this.id = id;
this.name = name;
}
public TestUser(int id, String name, int age, char sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public static void main(String[] args) {
TestUser s1 = new TestUser(1001,"zxp");
TestUser s2 = new TestUser(1003,"zxp",'男');
TestUser s3 = new TestUser(1002,"zxp",18,'男');
}
}
注意事项:
- 如果方法构造中形参与属性名相同,需要使用this关键字区分属性与形参。this.id表示属性id,id表示形参id。
this关键字
this的用法
-
在普通方法中,this总是指向调用该方法的对象
-
在构造方法中,this总是指向正要初始化的对象
this的其他要点
- this()调用重载的构造方法,避免相同的初始化代码,但只能在构造方法中用,并且必须位于构造方法的第一句
- this不能用于static方法中
- this是作为普通方法的"隐式参数",有系统传入到方法中
/**
* 测试this的使用
*/
package com.zxp;
public class TestThis {
int a;
int b;
int c;
public TestThis() {
System.out.println("你妈妈喊你回家吃饭");
}
public TestThis(int a,int b){
//TestThis();//不能这样调用构造方法,
this();//这样可以调用无参构造,并且this()必须放在第一位
//a = a,不可以这样使用前面的a是构造方法里面的成员变量,而不是局部变量
this.a = a;
this.b = b;
}
public TestThis(int a, int b, int c) {
this(a,b);
this.c = c;
}
public void kickball(){
System.out.println("我在踢球,为我加油!");
}
public static void main(String[] args) {
TestThis t1 = new TestThis(2,3);
t1.kickball();
}
}