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

    java中this有三个作用:

    1. 区别全局变量和局部变量

    public class TestThis {
        int a,b,c;
        TestThis(int a,int b){
            this.a = a; //this代表当前构造的对象
            this.b = b;
        }
    }

       2.在方法中this表示当前的对象调用该方法,this表示当前对象     

    public class TestThis {
        int a,b,c;
    
     void sing(){
        }
        void  eat(int a,int b,int c){
            this.sing();    //在普通方法中,调用动态方法
        }
    }

       3.构造器中this()表示调用形式参数相同的同一个类中的另一个构造器,这样就可以代码复用,就拿下面这段代码来说, this()就表示调用该类中 名称是TestThis、形参是空的构造器   让里面的代码在这个有参的构造器中再跑一遍

    public class TestThis {
        int a,b,c;
       
        TestThis(){
            System.out.println("我是无参构造器");
        }
        TestThis(int a,int b){
            this();
            this.a = a; 
            this.b = b;
        }
    }

        补:

        在方法中this表示谁调用该方法 this就代表谁

        例如:public void show(){

            Synchronized(this){

            ……}

           }

        同步代码块表示 哪个对象调用该方法  就得到哪个对象的对象锁

  • 相关阅读:
    Java中IO流的总结
    Java常用集合体系以及相互区别
    TreeMap集合特点、排序原理
    HashMap集合
    TreeSet集合
    redis 数据类型详解 以及 redis适用场景场合
    You need tcl 8.5 or newer in order to run the Redis test
    PHP 获取二维数组中某个key的集合
    Linux 定时任务
    phpmailer邮件类
  • 原文地址:https://www.cnblogs.com/pxb2018/p/10513679.html
Copyright © 2011-2022 走看看