2021-03-04

Java this 的使用问题

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

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

 









原文转载:http://www.shaoqun.com/a/603602.html

跨境电商:https://www.ikjzd.com/

ola:https://www.ikjzd.com/w/2103

pocket:https://www.ikjzd.com/w/1903


review代码的时候,对对象自己的方法调用是否使用this有了点争议,重新看了下thinkinjava,看到了下面的一句话,我是非常认同这句话的,google了一下,发现确实有人问着问题:https://stackoverflow.com/questions/516768/using-this-with-methods-in-java。一般情况下可能会考虑由于子类重载会导致未知问题,其实并不会导
feedly:https://www.ikjzd.com/w/754
myshow:https://www.ikjzd.com/w/2235
黄劲:https://www.ikjzd.com/w/2426
Shopee运费补贴政策:https://www.ikjzd.com/w/2644
亚马逊爆款有哪些潜质?5大标准来验证,90%的大卖都在用:https://www.ikjzd.com/home/114519
东南亚电商市场蛋糕这么大,到底哪个平台值得做?​:https://www.ikjzd.com/home/109859

No comments:

Post a Comment