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
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值