Java学习笔记:构造方法,this
@(Java)
构造方法作用就是对类进行初始化。
不管你是否自定义构造方法,所有的类都有构造方法,因为Java自动提供了一个默认构造方法,默认构造方法的访问修改符和类的访问修改符相同(类为 public,构造函数也为 public;类改为 private,构造函数也改为 private)
一旦定义了自己的构造方法,默认构造方法就会失效
- 通过new关键字调用
- 构造器虽然有返回值,但是不能定义返回值类型(返回值的类型肯定是本类),不能在构造器里使用return返回某个值。
- 如果我们没有定义构造器,则编译器会自动定义一个无参的构造函数。如果已定义则编译器不会自动添加
- 构造器的方法名必须和类名一致
构造方法的重载
public class User {
int id; // id
String name; // 账户名
String pwd; // 密码
public User() {
}
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public static void main(String[] args) {
User u1 = new User();
User u2 = new User(101, "zhxmdefj");
User u3 = new User(100, "zhx", "123456");
}
}
对象创建的过程
构造方法是创建Java对象的重要途径,通过new关键字调用构造器时,构造器也确实返回该类的对象,但这个对象并不是完全由构造器负责创建。创建一个对象分为如下四步:
- 分配对象空间,并将对象成员变量初始化为0或空
- 执行属性值的显式初始化
- 执行构造方法
- 返回对象的地址给相关的变量
this
this的本质就是“创建好的对象的地址”
由于在构造方法调用前,对象已经创建。因此,在构造方法中也可以使用this代表“当前对象”
this最常的用法:
- 在程序中产生二义性之处,应使用this来指明当前对象
- 普通方法中,this总是指向调用该方法的对象
- 构造方法中,this总是指向正要初始化的对象。
- 使用this关键字调用重载的构造方法,避免相同的初始化代码。但只能在构造方法中用,并且必须位于构造方法的第一句。
- this不能用于static方法中。
this()调用重载构造方法
public class TestThis {
int a, b, c;
TestThis() {
}
TestThis(int a, int b) {
// TestThis(); 这样无法调用构造方法
this(); // 调用无参的构造方法,并且必须位于**第一行**
// a = a;错误,a指局部变量,就近
this.a = a;//this指当前的对象,int a, b, c;里的a
this.b = b;
}
TestThis(int a, int b, int c) {
this(a, b);//构造器调用另一个构造器
//必须为第一句
/*
this.a = a;
this.b = b;
*/
this.c = c;
}
void sing() {
}
void eat() {
this.sing(); // 调用本类中的sing();
System.out.println("你妈喊你回家吃饭!");
}
public static void main(String[] args) {
TestThis hi = new TestThis(2, 3);
hi.eat();
}
}