Java基础学习(十四)面向对象之this关键字

关键字this

1.使用在类中,可以用来修饰属性、方法、构造器

2.表示当前对象或者是当前正在创建的对象

3.当形参与成员变量重名时,如果在方法内部需要使用成员变量,必须添加this来表明该变量时类成员

4.在任意方法内,如果使用当前类的成员变量或成员方法可以在其前面添加this,增强程序的阅读性

5.在构造器中使用“this(形参列表)”显式的调用本类中重载的其它的构造器

    5.1 要求“this(形参列表)”要声明在构造器的首行!

    5.2 类中若存在n个构造器,那么最多有n-1构造器中使用了this。

【例子】

  1. public class TestPerson {
  2.     public static void main(String[] args) {
  3.         Person p1 = new Person();
  4.         System.out.println(p1.getName() + ":" + p1.getAge());
  5.         Person p2 = new Person("DannyWu"1);
  6.         int temp = p2.compare(p1);
  7.         System.out.println(temp);
  8.     }
  9. }
  10. class Person {
  11.     private String name;
  12.     private int age;
  13.     public Person() {
  14.         this.name = "DannyWu";
  15.         this.age = 1;
  16.     }
  17.     public Person(String name) {
  18.         this();
  19.         this.name = name;
  20.     }
  21.     public Person(String name, int age) {
  22.         this(name);
  23.         this.age = age;
  24.     }
  25.     public String getName() {
  26.         return name;
  27.     }
  28.     public void setName(String name) {
  29.         this.name = name;
  30.     }
  31.     public int getAge() {
  32.         return age;
  33.     }
  34.     public void setAge(int age) {
  35.         this.age = age;
  36.     }
  37.     public void eat() {
  38.         System.out.println("eating");
  39.     }
  40.     public void sleep() {
  41.         System.out.println("sleeping");
  42.         this.eat();
  43.     }
  44.     // 比较当前对象与形参的对象的age谁大。
  45.     public int compare(Person p) {
  46.         if (this.age > p.age)
  47.             return 1;
  48.         else if (this.age < p.age)
  49.             return -1;
  50.         else
  51.             return 0;
  52.     }
  53. }
weinxin
我的微信
有问题微信找我
DannyWu

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

Protected with IP Blacklist CloudIP Blacklist Cloud