希望在方法内部获得对当前对象的引用:this关键字
注:
1.方法内部使用,表示对“调用方法的那个对象”的引用;
2.如果在方法内部调用同一个类的另一个方法,不必使用this关键字,直接调用即可。
用途:
1.返回当前对象,便于继续调用方法
public class TestThisOne {
public static void main(String[] args) {
Student xiaoMing = new Student( );
xiaoMing.incrementAge().incrementAge().incrementAge().printAge();
}
}
class Student{
int age =0;
Student incrementAge(){
this.age++;
return this;
}
void printAge(){
System.out.println("age ="+this.age);
}
}
2.将当前对象传递给其他方法
public class TestThisTwo {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}
class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
System.out.println("Eat a peeled apple");
}
}
class Peeler {
static Apple peel(Apple apple){
System.out.println("peeled an apple");
return apple;
}
}
class Apple {
Apple getPeeled() {
return Peeler.peel(this);
}
}
3.在构造器中调用构造器,可在一个类含有多个构造器且不希望有重复代码的情况下使用
public class TestThisThree {
public static void main(String[] args) {
new Animal("Jerry",6).makeSelfIntroduction();
}
}
static class Animal{
private String name; //私有属性 名字
private int age; //私有属性 年龄
Animal(){
}
Animal(String name){ //构造重载函数,字符串参数.
this.name = name;
}
Animal(String name, int age){ //构造重载函数,字符串与整型参数.
this(name);
this.age = age;
}
public void makeSelfIntroduction(){
System.out.println("my name is:"+this.name+",and i'm "+this.age+" years old!");
}
}
}