实例,就是一个真实的对象。比如我们都是“人”,而你和我其实就是“人”类的实例了。实例化就是创建对象的过程,使用new关键词类创建。
创建一个对象有如下四步:
1.分配对象空间,并将对象的成员变量初始化为0或空;
2.执行属性值的显示初始化;
3.执行构造方法;
4.返回对象的地址给相关的变量。
this的本质就是“创建好的对象的地址”;由于在构造方法调用前,对象已经创建,因此,在构造方法中也可以使用this代表“当前对象"。
public class TestThis {
public static void main(String[] args) {
TestThis h = new TestThis(1,2,3);
h.eat();
}
int a, b, c;
TestThis(int a, int b) {
this.a = a;//当前对象
this.b= b;
//this.c = c;
}
/*(public)*/TestThis(int a, int b, int c) { //public为访问权限(公共),加不加都行
this(a, b); //调用构造器,且必须放在前面
this.c = c;
}
void call() {
}
void eat() {
this.call();
System.out.println("你妈妈喊你回家吃饭!");
}
}
运行结果
你妈妈喊你回家吃饭!