Java基础—This关键字

希望在方法内部获得对当前对象的引用: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!");
        }

    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值