this

作者: Mtllll | 来源:发表于2019-03-06 21:19 被阅读0次
    • This关键字
      表示当前对象
      主要存在两个位置:
      1.构造器中:就表示当前创建的对象.
      2.方法中:哪一个对象调用this所在的方法,那么此时this就是哪一个对象
    public class Calculate {
        String name;
        Calculate(String name)
        {
           this.name=name;//如果是name=name输出结果是null
        }
    
        public static void main(String[] args) {
            Calculate c=new Calculate("lucy");
            System.out.println(c.name);
    
    
        }
    }
    

    使用this:
    a.解决成员变量和参数(局部变量)之间的二义性
    b.同类中实例方法互相调用(此时可以省略this,但不建议)
    c.将this作为参数传递给一个方法
    d.将this作为方法的返回值(链式方法编程)
    e.构造器重载的互调tjis(参数)必须写在构造方法的第一行
    f.static和this不能一起使用
    当字节码被加载进JVM,static成员就已经存在了
    但是此时对象还没有创建,没有对象,就没this.

    相关文章

      网友评论

          本文标题:this

          本文链接:https://www.haomeiwen.com/subject/nbyqgxtx.html