zoukankan      html  css  js  c++  java
  • java中this的用法

    

    用类名定义一个变量的时候,定义的应该只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法,那们类里面是够也应该有一个引用来访问自己的属性和方法纳?呵呵,JAVA提供了一个很好的东西,就是 this 对象,它可以在类里面来引用这个类的属性和方法。

    this:指代当前对象,哪个对象调值的就是哪个对象

              在方法中(包括构造方法)访问成员变量前默认有个this.

    范例:Cell c = new Cell();

        c.row = 2;

        c.col = 5;

        c.drop();

        c.moveLeft(3);

        String str = c.getCellInfo();

        class Cell{

           int row;

           int col;

           void drop(){

           this.row++;//相当于c.row++;     在方法中访问成员变量前默认有个this.

           void moveLeft(int n){

           this.col-=n;// 相当于c.col-=n;     在方法中访问成员变量前默认有个this.

    }

    }

    }


      this的用法:

              1)this.成员变量---------访问成员变量


    范例:成员变量:写在类中,方法外

             局部变量:方法中

             成员变量和局部变量可以同名

    class Cell{

        int row;

        int col;

        Cell(int row,int col){

             this.row = row;

             this.col  = col;

        }

    }



    Cell c = new Cell(2,5);//相当于Cell c = new Cel();

                                              c.row = 2;

                                              c.col = 5;

    class Cell{

         int row;

         int col;

    Cell(int row,int col){

         this.row = row; //   c.row =2;

         this.col = col;//   c.col = 5;

       }

         void drop(){

               this.row++;//   c.row = c.row+1;

       }

    }


              2)this.方法名()------调用方法(一般不用)

              3)this()----------------调用构造方法(没有点!!!)


    Cell c1 = new Cell();

    Cell c2 = new Cell(3);

    Cell c3 = new Cell(2,5);


    class Cell{

    int row;

    int col;

    Cell(){

        row = 0;

        col =0;

    }

    Cell(int n){

       row = 0;

       col  = 0;

    }

    Cell(int n){

    row = n;//       this(n,n);调构造方法Cell(int row,int col)

    col = n;

    Cell(int row,int col){

    this.row = row;//       重名时不能省略

    this.col = col;

    }

    }

    }


  • 相关阅读:
    javaweb消息中间件——rabbitmq入门
    virtual box 桥接模式(bridge adapter)下无法获取ip(determine ip failed)的解决方法
    Apache Kylin本地启动
    git操作
    Java学习总结
    Java中同步的几种实现方式
    hibernate exception nested transactions not supported 解决方法
    vue 中解决移动端使用 js sdk 在ios 上一直报invalid signature 的问题解决
    cookie 的使用
    vue 专门为了解决修改微信标题而生的项目
  • 原文地址:https://www.cnblogs.com/KindGod/p/5493725.html
Copyright © 2011-2022 走看看