《Java基础知识》Java this关键字详解
this 关键字用来表示当前对象本身,或当前类的一个实例,通过this可以调用对象的所有方法和属性。
例如:
public class Demo {
private int x = 10;
private int y = 15;
public void sum(){
//通过this获取成员变量,this可以省略。
int z = this.x + this.y;
System.out.println("x+y = "+z);
}
public static void main(String[] args) {
Demo demo = new Demo();
demo.sum();
}
}
运行结果:
使用this区分同名变量
public class Demo {
private String name;
private int age;
public Demo(String name,int age){
//this不能省略,this.name 指的是成员变量, 等于后面的name 是传入参数的变量,this可以很好的区分两个变量名一样的情况。
this.name = name;
this.age = age;
}
public static void main(String[] args){
Demo demo = new Demo("微学院",3);
System.out.println(demo.name + "的年龄是" + demo.age);
}
}
运行结果:
this作为方法名来初始化对象
public class Demo {
private String name;
private int age;
public Demo(){
/**
* 构造方法中调用另一个构造方法,调用动作必须置于最起始位置。
* 不能在构造方法之外调用构造方法。
* 一个构造方法只能调用一个构造方法。
*/
this("微学院",3);
}
public Demo(String name,int age){
this.name = name;
this.age = age;
}
public static void main(String[] args){
Demo demo = new Demo();
System.out.println(demo.name + "的年龄是" + demo.age);
}
}
运行结果:
this作为参数传递
class Person{
public void eat(Apple apple){
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
}
class Peeler{
static Apple peel(Apple apple){
return apple;
}
}
class Apple{
Apple getPeeled(){
//传入this,就是传入Apple。
return Peeler.peel(this);
}
}
public class This{
public static void main(String args[]){
new Person().eat(new Apple());
}
}
this 用法就到这里。