// this只能用于实例方法中 谁调用这个方法谁就是this
// this 代表的是当前对象
public class ThisTest01
{
public static void main(String[] args)
{
Customer c1 =new Customer("张三");
c1.shopping();
Customer c2=new Customer("李四");
c2.shopping();
}
}
// 定义一个顾客类
class Customer
{
String name;
// 构造方法
public Customer()
{}
public Customer(String s)
{
name=s;
}
// 顾客购物的方法(实例方法)
public void shopping()
{
System.out.println(this.name+"正在购物"); // this可以省略
}
}
为什么静态方法不能用this 去访问对象??
原因:静态方法不需要创建对象就可以访问 而this 本身访问的就是对象
为了是形参见名知意 引入this
public class ThisTest02
{
public static void main(String[] args)
{
student s1=new student();
s1.setNo(112);
s1.setName("张三");
System.out.println(s1.getNo());
System.out.println(s1.getName());
}
}
// 学生类
class student
{
private int no;
private String name;
// 无参构造
public student()
{}
// 有参构造
public student(int no,String name)
{
this.no=no;
this.name=name;
}
// set和get方法
public int getNo()
{
return no;
}
public void setNo(int no)
{
this.no=no;// 不可以省略
}
public String getName()
{
return name;// this可以省略
}
public void setName(String name)
{
this.name=name;
// this代表当前对象
}
}
this用在构造方法中解决代码重复
/*
this也可以用于构造方法中 语法:this(); 注意:this只能出现在构造方法的第一行
*/
public class ThisTest03
{
public static void main(String[] args)
{
Date s1=new Date();
s1.detail();
Date s2=new Date(2008,11,23);
s2.detail();
}
}
//定义一个Date类
class Date
{
private int year;
private int month;
private int day;
// 无参构造
public Date()
{
//this.year=1970;
//this.month=1;
//this.day=1;
// 用一行解决
this(1977,1,1);
}
// 有参构造
public Date(int year,int month, int day)
{
this.year=year;
this.month=month;
this.day=day;
}
public void setYear(int year)
{
this.year=year;
}
public int getYear()
{
return year;
}
public void setMonth(int month)
{
this.month=month;
}
public int getMonth()
{
return month;
}
public void setDay(int day)
{
this.day=day;
}
public int getDay()
{
return day;
}
// 普通方法打印
public void detail()
{
System.out.println(year+"年"+month+"月"+day+"日");
}
}