Java this 的使用问题

时间:2021-03-05 12:53:24   收藏:0   阅读:0

review 代码的时候,对对象自己的方法调用是否使用this有了点争议,重新看了下think in java,看到了下面的一句话,

技术图片

 

我是非常认同这句话的,google了一下,发现确实有人问着问题:https://stackoverflow.com/questions/516768/using-this-with-methods-in-java

一般情况下可能会考虑由于子类重载会导致未知问题,其实并不会导致什么问题。因为编译器在编译的时候,会自动把当前对象当做方法调用的第一个参数,这个和用this来调用是一样的,编译器已经帮助做过一次了,就没有必要再去做一次。

看看下面的例子,不管加不加this,最后结果都是一样的,所以没遇到特殊情况,就不要加this了,这样也会保持代码的统一,利于维护,为了一个可能几乎不会碰到的“例外”增加代码不统一性,没有必要。

技术图片
class Parent {
 
    public void eat(){
        System.out.println("Parent eat");
    }
 
    public void showEat(){
        this.eat();
    }
 
    public void showEat1(){
        eat();
    }
}
 
class Child extends Parent {
 
    @Override
    public void eat(){
        System.out.println("Child eat");
    }
}
 
public class Application {
 
    public static void main(String[] args){
        Parent p = new Parent();
        p.eat(); // Parent eat
        p.showEat();// Parent eat
        p.showEat1();// Parent eat
 
        Parent pc = new Child();
        pc.eat(); // Child eat
        pc.showEat();// Child eat
        pc.showEat1();// Child eat
 
 
        Child c = new Child();
        c.eat(); // Child eat
        c.showEat();// Child eat
        c.showEat1();// Child eat
    }
}
View Code

注意:代码的可为维护性,永远比使用一些特殊功能要重要,切记,切记。

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!