this关键字

1. 表示类中的属性和调用方法

class People{
    private String name;
    private int age;
    //通过this来调用本类中的属性
    public  People(String name ,int age){
        this.name  = name;
        this.age = age;
    }
    //通过this来调用本类中的方法
    public void tell(){
        System.out.println("姓名:"+this.getName()+"    年龄:"+this.getAge());
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}

2. 调用本类中的构造方法

在上面的代码中加入一个重载的构造方法:

    public People(){
        System.out.println("无参数构造方法");
    }

然后想要在调用这个类的时候就执行这个重载方法只需要用this();来做到调用本类的构造方法。
即在1的代码中的第8行前面加上this();
**注意:this();的位置必须处于构造方法的第一位。
**

3. 表示当前对象

class Peoople1{
    public void tell(){
        System.out.println(this);
    }
}
public class ThisDemo02 {
   public static void main(String[] args){
       Peoople1 p = new Peoople1();
       System.out.println(p);
       p.tell();
   }
}

这个输出的数据为:

com.jikexueyuan.com.jikexueyuan.thisDemo.Peoople1@4554617c
com.jikexueyuan.com.jikexueyuan.thisDemo.Peoople1@4554617c

即两个out输出的数据是一样的,则代码第3行System.out.println(this);中的this代表的是当前对象。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇