MENU

this关键字

June 5, 2018 • Read: 2731 • Java阅读设置

1.this关键字作用

  • 调用本类中的属性和调用方法
  • 调用本类中的构造方法(一般指重载的构造方法)
  • 表示当前对象

2.示例

/*this关键字的第1,2两点用法示例*/
class Person{
    private int age;
    public getAge(){
        return age;
    }
    Person(int age){
        this();//指的是无参的构造方法,并且当用this调用本类构造方法的时候,只能放构造方法的首行
        this.age = age;//this.age指的是类中的成员变量age
    }
    person(){
        System.out.println("无参数的构造方法被调用");
    }
    public void tell(){
        System.out.println("年龄:" + this.getAge());
    }
}
public static void main(String args[]){
    Person p = new Person(15);//无参数的构造方法被调用
    p.tell();//年龄:15
}
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment