zoukankan      html  css  js  c++  java
  • this关键字

    this:
    1.使用在类中,可以用来修饰属性、方法、构造器
    2.表示当前对象或者是当前正在创建的对象
    3.当形参与成员变量重名时,如果在方法内部需要使用成员变量,必须添加this来表明该变量时类成员
    4.在任意方法内,如果使用当前类的成员变量或成员方法可以在其前面添加this,增强程序的阅读性
    5.在构造器中使用“this(形参列表)”显式的调用本类中重载的其它的构造器
    >5.1 要求“this(形参列表)”要声明在构造器的首行!
    >5.2 类中若存在n个构造器,那么最多有n-1构造器中使用了this。

    public class TestPerson {
    public static void main(String[] args) {
    Person p1 = new Person();
    System.out.println(p1.getName() + ":" + p1.getAge());

    Person p2 = new Person("BB",23);
    int temp = p2.compare(p1);
    System.out.println(temp);
    }
    }
    class Person{

    private String name;
    private int age;

    public Person(){
    this.name = "AA";
    this.age = 1;
    }

    public Person(String name){
    this();
    this.name = name;
    }
    public Person(String name,int age){
    this(name);
    this.age = age;
    }

    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    public void eat(){
    System.out.println("eating");
    }
    public void sleep(){
    System.out.println("sleeping");
    this.eat();
    }
    //比较当前对象与形参的对象的age谁大。
    public int compare(Person p){
    if(this.age > p.age)
    return 1;
    else if(this.age < p.age)
    return -1;
    else
    return 0;
    }

    }

  • 相关阅读:
    (4.7)怎么捕获和记录SQL Server中发生的死锁?
    SQLSERVER排查CPU占用高的情况
    (4.6)sql server索引缺失提示
    (4.14)向上取整、向下取整、四舍五入取整的实例
    mysql大致学习路径
    (2)linux未使用eth0,未使用IPV4导致无法连接
    (4.13)sql server参数嗅探(parameter sniffing)
    完美女人
    关于box-sizing
    什么是担当
  • 原文地址:https://www.cnblogs.com/wzlbigdata/p/8383610.html
Copyright © 2011-2022 走看看