this关键字

1.关键字,代表当前类的对象

  2.可以代表当前类还没有产生的对象,或者当前类刚创建的对象,或者当前类正在使用的对象。This是灵活的代指(虚拟--地址值),可以指代当前类正在活动的对象

  3.this语句---在同一个类中的构造方法里调用别的构造方法,首行

package cn.tedu.object;

public class ThisDemo {
    //创建对象
    public static void main(String[] args) {
        Student s1=new Student();
        //this可以代表当前类刚创建的对象
        System.out.println("s1:"+s1);
        //创建对象
        Student s2=new Student("TOM");
        //this是一个灵活的指代
        System.out.println("s2:"+s2);
        //this指代成当前类正在使用的对象
       s1.study();
    }
}

//代表学生类
class Student{
    //属性
    String name;
    int age;
    char gender;
    //无参构造
    public Student(){
        System.out.println("this:"+this);
    }
    //有参构造
    public Student(int age){
         //this();
    }
    //有参构造
    public Student(String name){
        //调用别的构造方法
        //Student();调用不了(在创建对象时调用)
        //this语句---调用别的构造方法   要在首行
        this(1);//给定对应的类型值(因为方法名都一样)
        this.name=name;
        System.out.println("this:"+this);
    }
    //方法
    public void study(){
        //this可以代表当前类还没有创建的对象
        System.out.println(this.name+"在睡觉");
        System.out.println("this:"+this);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值