this关键字

来源:互联网 发布:鲨鱼记账怎么导出数据 编辑:程序博客网 时间:2024/06/05 06:59

-----------siwuxie095

  

  

  

this 关键字:

  

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

  

2)表示本类中的构造方法

  

3)表示当前对象

  

  

  

代码1

  

package com.siwuxie095.thisdemo;

  

class People{

private String name;

privateint age;

 

public People(String name,int age) {

//代表构造方法,且必须放在首行,否则无法通过编译

this();

this.name=name;

this.age=age;

}

 

public People() {

System.out.println("无参构造方法");

}

 

public String getName() {

return name;

}

publicvoid setName(String name) {

this.name = name;

}

publicint getAge() {

return age;

}

publicvoid setAge(int age) {

this.age = age;

}

 

publicvoid tell() {

System.out.println("姓名:"+this.getName()+"年龄:"+this.getAge());

}

 

}

  

public class ThisDemo01 {

  

public staticvoid main(String[] args) {

People p=new People("张三",30);

p.tell();

}

  

}

  

  

运行一览:

  

  

  

  

代码2

  

package com.siwuxie095.thisdemo;

  

class PeopleX{

 

publicvoid tell() {

//this表示当前对象

System.out.println(this);

}

}

  

public class ThisDemo02 {

  

public staticvoid main(String[] args) {

PeopleX p=new PeopleX();

//输出一致,可以通过这种方式比较两个对象是不是同一对象

System.out.println(p);

p.tell();

}

  

}

  

  

运行一览:

  

  

  

  

  

  

【made by siwuxie095】

0 0
原创粉丝点击