1、this关键字可以访问当前类中的属性(也叫成员变量或实例变量)
如:this.id 表示当前这个对象的id属性
2、this关键字可以访问当前类中的方法(也叫成员方法或实例方法)
如:dispaly(); 等价于this.display();
注意:1)如果在同一个类中访问成员(成员变量和成员方法),并且成员没有使用static修饰,则默认前面添加this关键字。
2)在同一个类中,局部变量和成员变量可以同名,但是局部变量优先,如果非要访问成员变量,则必须添加this关键字。
3、this关键字可以访问当前类中的构造方法,如下:
this();
this(brand,price);
注意:1)如果使用this关键字访问构造方法,则必须编写在构造方法中,并且放在第一行。
代码分享:
class Computer{ //成员变量 String id; String brand; double price; String color; //构造方法 public Computer(String brand,double price){ this.brand=brand; this.price=price; System.out.println("brand:::"+brand); System.out.println("price:::"+price); } public Computer(String id,String brand,double price,String color){ this(brand,price); //如果使用this关键字访问构造方法,则必须编写在构造方法中,并且放在第一行。 this.id=id; this.color=color; } //如果在同一个类中访问成员(成员变量和成员方法),并且成员没有使用static修饰,则默认前面添加this关键字。 //同一个类中的属性和方法是直接方法 public void show(){ System.out.println("电脑信息show如下:"); System.out.println("id]:"+id); System.out.println("brand]:"+brand); System.out.println("price]:"+price); display(); System.out.println("--------"); this.display();//dispaly(); 等价于this.display(); System.out.println("---------"); } public void display(){ System.out.println("电脑信息display如下:"); System.out.println("id}:"+this.id);//this代表当前这个对象 System.out.println("brand}:"+this.brand); System.out.println("price}:"+this.price); System.out.println("color}:"+this.color); } } public class ThisTest { public static void main(String[] args){ Computer c=new Computer("001","Lenovo",90,"银色"); c.show(); //c.display(); } }