Blog of CodeJELLOW’S ENGINEERING NOTES
← 返回文章

java中this关键字的作用

this 是什么? 在Java中 this 关键字的作用和其词义接近 在方法内部使用,即这个方法所属对象的引用 在构造器内部使用,表示改构造器正在初始化对象 this表示当前对象,可以调用类的属性,方法,构造器 public class person { pu…

本文目录 ⌄

    this 是什么?

    在Java中 this 关键字的作用和其词义接近

    • 在方法内部使用,即这个方法所属对象的引用
    • 在构造器内部使用,表示改构造器正在初始化对象

    this表示当前对象,可以调用类的属性,方法,构造器

    TEXT
    public class person {
     public person(int age,String name) {
     this.age = age;    //this.age表示实参,age表示形参
     this.name = name;
     }
    
     int age;
     String name;
     
     public void setName(String name) {
     this.name = name;
     }
     public void setName1(String name) {
     this.setName(name);  //调用 setName 函数 括号里的name是 setName1(name)的形参 
     }
     public void showInfo() {
     System.out.println("姓名"+this.name);//这个this.name是类里面定义的 String name; 
     }
    }

    什么时候使用this关键字

    在方法内需要用到调用该方法的对象时,就使用this

    当形参与成员变量重名时,如果在方法内部需要使用成员变量,必须添加this来表明该变量是类变量。 例如程序代码中的 this.age = age; 即使用this关键字来说明变量。

    TEXT
    public class person {
     public person(int age,String name) {
     this.age = age;      //this.age表示实参,age表示形参
     this.name = name;
     }
    }

    在任意方法内,如果当前类的成员变量 或成员方法,可以在其前面添加this,增强程序的阅读性。 例如 this.setName(name); 其中括号中的name是形参, this.setName() 表示调用person类中的函数。

    TEXT
    public class person {
     int age;
     String name;
     
     public void setName(String name) {
     this.name = name;
     }
      public void setName1(String name) {
    		this.setName(name);
    	}
    }

    this可以作为一个类中,构造器相互调用的特殊格式。

    TEXT
    
    public class person {
     
     int age;
     String name;
     public person() {
               //无参构造
     }
     public person(int age) {
     this.name = name;
     }
     public person(String name) {
     this(); //调用public person()
     this.age = age;
     }
     public person(int age,String name) {
     this(1);//调用public person(int age)
     this.age = age;
     this.name = name;
     } 
    }

    注意:

    • 使用this( ) 必须放在构造器首行!
    • 使用this调用本类中其他的构造器,保证至少有一个构造器是不使用this的,即不能自己调用自己。
    通过 RSS 订阅更新 →