JAVA中this的用法

 在以下两种情况中可以使用this关键字(注:在被static(静态方法)声明的地方不能使用this)

第一:当构造函数的参数与对象的数据成员同名时,可以使用this,加以区分。

例如:

public class Student {
    String name; //对象数据成员
    String age; //对象数据成员
    String gender; //对象数据成员

    public Student(){      //无参数的构造方法 
        //this.name="nothing"; 
        //this.age="19"; 
        //this.gender="男";
        
        this(nothing,19,男); //直接赋值

}
    

    public Student(String name, String age, String gender) {   //有参数的构造方法 
        this.name = name;    //this.name是对象成员,name是构造函数参数
        this.age = age;      //this.age是对象成员,age是构造函数参数
        this.gender = gender; //this.gender是对象成员,gender是构造函数参数
        }                     //将构造函数中的参数赋值给对象的数据成员
}

说白了,this就是为了区分这两个同名不同物的东西而产生的。

第二:可以调用一个已经定义的构造函数,减少代码的重复性

例如:

public class Student{

        int age = 19;

        String name = "nothing";

        public Student(int age){

                        if(age > 18){

                        this.age = age;

                }

        }

        public Student(int age,String name){

                if(age > 18){                       //可用this(age);来代替

                        this.age = age;       

                }

                if(name != null){

                        this.name = name;       

                }

        }

}

我们发现红色代码是重复的,我们可以将这部分代码改写为this(age);

要是有多个构造函数,java就通过我们在this()的括号中给出的自变量类型与个数来判别,如果是this(age)那么就调用public Student(int age),如果是this(int age,String name),那么就调用public Student(int age,String name)。

(注:this()调用只能出现在构造函数第一行)

总结:1.构造函数的参数与对象的数据成员同名时;

           2.调用一个已定义的构造函数

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nothing8727

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值