zoukankan      html  css  js  c++  java
  • java基础之this的用法 10.13

    this:
    1.返回调用当前方法的对象的引用。
    public class Leaf{
    private int i=0;
    public Leaf increament(){
    i++;
    return this;
    }
    public static void main(String[] args){
    Leaf x= new Leaf();
    x.increment().print();
    Leaf y= new Leaf();
    y.increment().print();
    }
    }

    this表示Leaf类的实例 当执行x.increment(),this表示实例x的引用。同理执行y.increment(),this表示实例y的引用。

    2.在构造方法中调用当前类的其他构造方法.
    定义了3个person类的构造方法,分别是无参,有一个参数,有两个参数,实现代码的重复利用,使用this()和this(_name)来调用person()和person(String _name)
    在使用this调用其他的构造方法时,必须放在构造方法的开始处,否咋不会编译
    public class Person{
    private String name;
    private int age;
    private String sex;
    public Person(){
    sex="male";
    }
    public Person(String _name){
    this();
    name=_name;
    }
    public Person(String _name,int _age){
    this(_name);
    age=_age;
    }
    }
    3.当方法参数名和成员变量名相同,用于区分参数名和成员变量。
    setter方法的参数名和成员变量名相同,this.name表示成员变量名,name表示参数名。
    public class Person{
    private String name;
    privae int age;
    public void setName(String name){
    this.name=name;
    }
    public void setAge(int age){
    this.age=age;
    }
    }

  • 相关阅读:
    NOIP1996 第三题
    vijos P1071
    USACO 2.3
    NOIP2006 第二题(change)
    NOIP2006 第二题
    NOIP2005 第三题
    Building Block 动态规划
    砝码问题 Weight
    装箱问题(Packing DP)
    算法第二章上机实践报告
  • 原文地址:https://www.cnblogs.com/weijingboke/p/5955094.html
Copyright © 2011-2022 走看看