public class Customer {
String name;
public void shopping(){
System.out.println(name+"在购物");
//完整写法
//System.out.println(this.name+"在购物");
}
}
public class Customer_test {
public static void main(String[] args) {
Customer c1=new Customer();
c1.name="zhangsan";
c1.shopping();
Customer c2=new Customer();
c2.name="lisi";
c2.shopping();
}
}
运行结果:
zhangsan在购物
lisi在购物
内存分析

- this是一个引用,this是一个变量,this变量中保存了内存地址指向了自身,this存储在JVM堆内存java对象内部
- 创建100个java对象,每一个对象都有this,也就是说有100个不同的this
- this可以出现在“实例方法”当中,this指向当前正在执行这个动作的对象(this代表当前对象)
- this在多数情况下都是可以省略不写的
- this不能使用在带有static的方法当中
在带有static的方法当中不能"直接"访问实例变量和实例方法,因为实例变量和实例方法都需要对象的存在
而static的方法中是没有this的,也就是说当前对象是不存在的,自然也是无法访问当前对象的实例变量和实例方法
反例:
public class ThisTest2{
String name;
public void doSome(){}
public static void main(String[] args){
System.out.println(name);
doSome();
//都无法访问
}
}
"this."用来区分局部变量和实例变量的时候不能省略
private int id;//实例变量
public void setId(int id){
this.id=id;
}//等号前面的this.id是实例变量id
//等号后面的id是局部变量id
this可以用在哪里
1.可以用在实例方法中,代表当前对象[语法格式:this.]
2.可以用在构造方法中,通过当前的构造方法调用其他的构造方法[语法格式:this(实参);],而this()这种语法只能出现在构造函数第一行
示例:
public class Date {
private int year;
private int month;
private int day;
public Date(){
this.year=1970;
this.month=1;
this.day=1;
}
public Date(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
}
public void print(){
System.out.println(this.year+"年"+this.month+"月"+this.day+"日");
}
}
public class Date_test {
public static void main(String[] args) {
Date time1=new Date();
time1.print();
Date time2=new Date(2008,8,8);
time2.print();
}
}
运行结果:
1970年1月1日
2008年8月8日
time1调用无参构造,time2调用有参构造
下面我们来对无参构造进行优化
this.year=1970;
this.month=1;
this.day=1;
将上面这部分改为this(1970,1,1);
可以达到同样的效果
this关键字用来表示当前对象本身,或当前类的一个实例,通过this可以调用本对象的所有方法和属性。
public class Solution {
public int x=10;
public int y=15;
public void sum(){
int z=this.x+this.y;
System.out.println("x+y="+z);
}
public static void main(String[] args) {
Solution sl=new Solution();
sl.sum();
}
}
运行结果:
x+y=25
在普通成员方法中使用this调用另一个成员方法
public class Student {
public String name;
public void doClass(){
System.out.println(name+"正在上课");
this.doHomeWork();
}
public void doHomeWork(){
System.out.println(name+"正在写作业");
}
public static void main(String[] args) {
Student stu1=new Student();
stu1.name="root";
stu1.doClass();
}
}
运行结果:
root正在上课
root正在写作业
在熟练敲代码之后,我们可以更方便快捷地写代码:
封装用到的set和get方法,还有构造方法都可以在IDEA中自动生成,在代码空白处右键,选择生成(generate),在里面就可以选择要生成的代码了。
一些快捷方式:
ctrl+d -复制当前行代码
psvm或main +回车 -public static void main(String[] args) {}
sout +回车 -System.out.println();
6万+

被折叠的 条评论
为什么被折叠?



