this关键字

this关键字

this关键字是代表当前对象的引用(地址)

public class Person{//(1)类名
        //(2)属性
        String name;
        int age;
        String gender;
        public Person(){
                System.out.println("this="+this);
        }
        
        //(3)行为
        public void eat(String content){
                System.out.println(name+"在吃"+content);
        }
        public void introduce(){
        
                System.out.println(name+"\t"+age+"\t"+gender);
        }
}

this关键字的作用:

  1. 使用本类的属性(this.name)this可以省略不写
  2. 使用本类的方法(this.eat())this可以省略不写
  3. 调用本类的其他构造方法this(),this(…),要求是构造方法中的第一行代码
  4. 用于区分成员变量和局部变量 this代表成员变量

this关键字在创建对象时,永远指的是当前对象,在调用成员方法时,永远指得是调用该方法的对象

public class Person{//(1)类名
        //(2)属性
        String name;
        int age;
        String gender;
        public Person(){
                System.out.println("this="+this);
        } 
        /*public static void fun(){ //static的方法中不能使用this
                System.out.println("this="+this);
        }*/
        /**方法定义处的参数为形参,方法调用处的参数为实参*/
        public Person(String name,int age,String gender){
                this(name,age); //调用本类的基它构造方法,要求必须是构造方法中第一句代码
                this.gender=gender;  //this关键字用于成员变量和局部变量
                                
        }
        public Person(String name,int age){
                this();//调用本类的无参构造方法
                this.name=name;
                this.age=age;
        }
        //(3)行为
        public void eat(String content){
                System.out.println(name+"在吃"+content);
        }
        public void introduce(){
                this.eat("MLT"); //调用本类中的其它成员方法 this可以省略不写
                eat("HG");//省略了this
                System.out.println(name+"\t"+age+"\t"+this.gender); //调用类的属性this也可以省略不写
        }
}
public class Test5 {
     public static void main(String[] args) {
             
          Person p1=new Person();//在创建对象时this指代的是p1
           Person p2=new Person();//在创建对象时this指代的是p2
           
           System.out.println(p1);
           System.out.println(p2);
           
           //在进行方法调用时,永远指代的是调用该方法的对象
           p1.introduce(); //this指代的是p1
           p2.introduce();//this指代的是p2
           
             
     }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值