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;
    }

    }

  • 相关阅读:
    C# 操作ini配置文件
    2015-2016跨年感想
    HTTP 状态码总结 (HTTP Status Codes)
    简单、精准、高效的使用搜索引擎,快速的找到你想要的结果
    ASP.NET前后台交互之JSON数据
    软件开发项目做需求分析的一点心得
    我是如何自学编程的“3遍读书法”
    C#中Request.ServerVariables详细说明及代理
    C#
    JavaScript如何计算两个日期间的时间差
  • 原文地址:https://www.cnblogs.com/wzlbigdata/p/8383610.html
Copyright © 2011-2022 走看看