java中的this关键字

  • 通过this关键字来解决局部变量名称冲突的问题

    public class Demo {
        int x = 100;//成员变量
        Demo(int x){//局部变量x与成员变量x重名
            this.x = x;//this.x表示的是成员变量的x,x表示的是局部变量x
            System.out.println(x);//输出50
        }
    
        public static void main(String[] args) {
           Demo d = new Demo(50);
        }
    }
    
  • 通过this关键字调用其它成员方法

    public class Demo {
        void  A(){
           System.out.println("我被调用啦");
       }
        void B(){
            this.A();//调用A方法
       }
        public static void main(String[] args) {
            Demo C = new Demo();
            C.B();
        }
    }
    //在B()方法中通过this.A()访问A()方法,注意此处的this关键字可以不写,效果是一样的。
    
    public class Demo {
        void  A(){
           System.out.println("我被调用啦");
       }
        void B(){
            A();
       }
        public static void main(String[] args) {
            Demo C = new Demo();
            C.B();
        }
    }
    
  • 在构造函数调用构造函数的时候,用this来调用

    public class Demo {
        static int x;
        static int y;
        Demo(int x , int y){
            this.x = x;
            this.y = y;
        }
        Demo(){
            this(1,3);//调用有参数的构造方法
            //注意this,只能写在第一句
        }
        public static void main(String[] args) {
            Demo D1 = new Demo();
            System.out.println(Demo.x);//1
            System.out.println(Demo.y);//3
            Demo D2 = new Demo(1,2);
            System.out.println(Demo.x);//1
            System.out.println(Demo.y);//2
        }
    }
    

    注意

    //1.this语句只能写在第一句
    //2.this语句调用构造函数只能在构造函数,里面调用,不能写在其他的方法里面
    //3.this语句不能在两个构造函数里面想换调用
    
    public class Demo {
        static int x;
        static int y;
        Demo(int x , int y){
            this();//不可以相互调用构造函数
            this.x = x;
            this.y = y;
        }
        Demo(){
            this(1,3);
        }
        public static void main(String[] args) {
            Demo D1 = new Demo();
            System.out.println(Demo.x);//1
            System.out.println(Demo.y);//3
            Demo D2 = new Demo(1,2);
            System.out.println(Demo.x);//1
            System.out.println(Demo.y);//2
        }
    }
    
posted on 2021-03-16 20:42  月下伊独舞  阅读(78)  评论(0编辑  收藏  举报