博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

日常问题之Java中的this到底有什么作用

Posted on 2021-04-25 21:23  通宵的达旦  阅读(1069)  评论(0)    收藏  举报

作用一:就是表示当前对象,当方法里面的局部变量和成员变量同名的时候,但是程序又需要在该方法里去覆盖这个成员变量,那么就必须使用this,以区分类的属性和方法中的参数。

/**
 * @author Ma Dejun
 * @date 2021年04月2021/4/25日 20:07
 */
public class thisFunc {
    /**
     *  第一种:当方法里面的局部变量和成员变量同名的时候,
     *  但是程序需要在该方法里去覆盖这个成员变量,那么就必须使用this
     */
   private String function;
   private int func_id;

   public thisFunc(String function, int func_id) {
        this.function = function;
        this.func_id = func_id;
    }

    public static void main(String[] args) {
        thisFunc tf = new thisFunc("this表示当前对象,其中this.function = function等式左边是属性名,右边是参数",1);
        System.out.println("this的功能"+tf.func_id+"就是"+tf.function);
    }

}

image

作用二:让类中的一个方法去访问类中的另一个方法。如果我们在以下程序中,不使用this关键字的前提下在anotherFunc()这个函数中去调用thisFunction( )这个函数,那么我们就一定需要一个thisFunc这个对象,因为没有使用static修饰的成员变量和方法都需要使用对象来调用。那么当我们调用anotherFunc( )的时候,一定会提供一个thisFunc对象,我们就可以直接使用这个已经创建好的对象,不需要再去重新创建这么一个对象,所以我们就可以使用this去在anotherFunc( )中调用该方法的对象。而且this可以省略不写,虽然可以不写,但是实际上编译运行的时候,还是把this关键字加上了。

/**
 * @author Ma Dejun
 * @date 2021年04月2021/4/25日 20:07
 */
public class thisFunc {
    /**
     *  第二种:让类的一个方法去访问该类的另一个方法或者实例变量;
     */
   public int  thisFunction(){

       return 1;
   }
   public  void anotherFunc(){
       int i = this.thisFunction();      System.out.println("我在anotherFunc()方法中调用了thisFunction():"+(i+1));
   }
    public static void main(String[] args) {
       thisFunc tf = new thisFunc();
       tf.anotherFunc();
    }
}

image

作用三:this(参数)这种语法可以完成对构造方法的调用,只能在一个构造方法中使用this语句来调用类的其他构造方法,而不能在实例方法中用this语句来调用类的其他构造方法,也不能通过方法名来直接调用构造方法。且this()只可以放在所有语句的第一行。

/**
 * @author Ma Dejun
 * @date 2021年04月2021/4/25日 20:07
 */
public class thisFunc {
    /**
     *  第三种:this()调用构造函数,不能在普通方法中这么使用,会报错!!
     */
    private String function;
    private int id;

    public thisFunc(String function, int id) {
        this.function = function;
        this.id = id;

    }
    public thisFunc() {
        this("在构造方法中调用有参构造",1);
    }
    public static void main(String[] args) {
       thisFunc tf = new thisFunc();
       System.out.println(tf.function+","+tf.id);
    }
}

image

注意:

image