this关键字
1.表示调用本类属性
只要在类中访问类的属性,一定要加上this关键字
class Person{
private String name;
private int age;
public Person(String name, int age){
//name = name 就近使用原则,找到最近的,形参一直等于形参
//age = age
this.name = name; //访问类的属性
this.age = age;
}
public void setName(String n){
name = n;
}
public String getname(){
return name;
}
public void setAge(int num){
if(num<=0 || num>=150){
age = 0;
}
else{
age = num;
}
}
public int getAge(){
return age;
}
public void getPersonInfo(){
System.out.println("姓名为:"+name+",年龄为:"+age);
}
}
public class test{
public static void main(String[] args){
//根据Person类生产一个对象
Person per1 = new Person("gx",20);
per1.getPersonInfo();
}
}
2.表示调用本类方法
a.调用普通方法 this.方法名(参数)
当有类的继承关系时,表示本类方法一定要加上this关键字
public void getPersonInfo(){
System.out.println("姓名为:"+name+",年龄为:"+age);
this.print(); //this可以不加
}
public void print(){
System.out.println("******");
}
b.调用构造方法 this(参数)(重要)
I.this调用构造方法,必须放在构造方法首行
class Person{
private String name;
private int age;
public Person(){
System.out.println("******");
}
public Person(String name){
//调用本类无参构造
this();
this.name = name;
}
public Person(String name, int age){
//调用本类一个参数的有参构造
this(name);
this.age = age;
}
public void setName(String n){
name = n;
}
public String getname(){
return name;
}
public void setAge(int num){
if(num<=0 || num>=150){
age = 0;
}
else{
age = num;
}
}
public int getAge(){
return age;
}
public void getPersonInfo(){
System.out.println("姓名为:"+name+",年龄为:"+age);
}
}
public class test{
public static void main(String[] args){
//根据Person类生产一个对象
Person per1 = new Person("gx",20);
per1.getPersonInfo();
}
}
II.this调用构造方法不允许成环
在java中没有明确说明,一个代码不允许出现2次
public Person(){
//调用本类一个参数的有参构造
this(name);
System.out.println("******");
}
public Person(String name){
//调用本类无参构造
this();
this.name = name;
}
public Person(String name, int age){
//调用本类一个参数的有参构造
this(name);
this.age = age;
}
3表示当前对象
class Person{
public void print(){
//this表示当前调用对象
System.out.println("【Person类的print方法】"+this);
}
}
public class test{
public static void main(String[] args){
Person per1 = new Person();
System.out.println("【main方法】"+per1);
per1.print();
System.out.println("=======================");
Person per2 = new Person();
System.out.println("【main方法】"+per2);
per2.print();
}
}