目录
一、提出问题
请看下段代码:
定义一个日期类Date:
public class Date {
public int year;
public int month;
public int day;
public void setDate(int year, int month, int day) {
year = year;
month = month;
day = day;
}
public void printDate() {
System.out.println(year+"/"+month+"/"+day);
}
}
Test测试类:
public class Test {
public static void main(String[] args) {
Date date = new Date();
date.setDate(2024,05,21);
date.printDate();
}
}
输出结果是2024/05/21吗?
并不是的,这是为什么呢?
因为这是在public void setDate(int year, int month, int day)
方法里面,采用局部变量优先的原则。并没有给成员变量赋值。
但是我们在变量前加上个this试试?
public class Date {
public int year;
public int month;
public int day;
public void setDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate() {
System.out.println(year+"/"+month+"/"+day);
}
}
这就达到了我们的目的。
二、this代表的是?
this 代表当前对象的引用.
当前对象是什么?谁调用(方法,变量),那么‘谁’就是对象。
上面 date 调用 setDate() 对象就是date。
加上this之后,this.year 指的是当前对象的year 也就是成员变量的year.
其实这个 this 是隐藏传递的。
只是在平常写方法的时候,省略掉了。
public void printDate() {
System.out.println(year+"/"+month+"/"+day);
}
养成好习惯:加上this
public void printDate() {
System.out.println(this.year+"/"+this.month+"/"+this.day);
}
三、this的用法
1.this访问当前对象的成员变量
2.this访问当前对象非静态的成员方法
public class Date {
public int year;
public int month;
public int day;
public void setDate(Date this,int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate() {
System.out.println(this.year+"/"+this.month+"/"+this.day);
}
public void test() {
//this访问当前对象的成员变量
System.out.println(this.year);
//this访问当前对象非静态的成员方法
this.printDate();
}
}
为什么是非静态的方法,因为静态的方法又叫类方法,静态的是不依赖于对象的,对象可以调用,类名也可以调用。但是对象调用不合理!!!
3.this访问当前对象的其他的构造方法
什么叫做构造方法?
构造方法,构造方法是对象在构造是调用的方法。
定义:
与普通方法最大的区别是无返回值!!!
修饰限定符 类名(参数列表...) {
//方法体
}
//普通方法定义:
修饰限定符 返回值 类名(参数列表...) {
//方法体
}
作用:对成员变量进行初始化。
构造方法分为有参数的构造方法和无参数的构造方法!
- 在创建一个类时,编译器会默认带有一个无参数的构造方法。
- 但是,只要你创建了一个带参数的构造方法,编译器就不默认分配无参的构造方法了!
public class Date {
public int year;
public int month;
public int day;
//无参数构造方法
public Date() {
}
//有参数构造方法
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate() {
System.out.println(this.year+"/"+this.month+"/"+this.day);
}
}
this访问当前对象的其他的构造方法是?
使用 this() 的形式 且规定:this() 只能出现在方法里的第一行
public class Date {
public int year;
public int month;
public int day;
//无参数构造方法
public Date() {
//调用有参数的构造方法
this(2024,05,21);
}
//有参数构造方法
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate() {
System.out.println(this.year+"/"+this.month+"/"+this.day);
}
}
四、对象创建的过程
1.为对象分配内存
2.调用合适的构造方法