thinkinjava--5.4this关键字

学习内容

1.this关键字只能在方法内部使用,表示对:调用方法的那个对象的引用。如果在方法内部调用同一个类的另外一个方法,就不必使用this,当前方法中的this会自动应用于同一类的其他方法。

即在同一个方法调用其他方法不必写成

eat(){
  this.bowl();
};

2.this的练习题

编写具有两个方法的类,在第一个方法内调用第二个方法两次:第一次调用时不使用this关键字,第二次调用时使用this关键字-- * 这里只是为了验证它是起作用的,你不应该在实践中使用这种方法。

public class Practice_this {
    public static void main(String args[]) {
        cat cat = new cat();
        cat.eat1();
        cat.eat2();
    }
}

class cat{
   void bark(){System.out.println("猫在叫");};
   void eat1(){
       bark();       
   };
   void eat2(){
       this.bark();       //this是cat对象的引用,这种写法实际上是多余的,不必要的
   };


 

猜你喜欢

转载自blog.csdn.net/stonennnn/article/details/80622880