this的应用[开发应用]
第一种应用: this.
(1)this :代表当前对象,类似于“我”,访问当前对象的属性和方法
(2)this. :用于本类中访问当前对象的属性和成员方法,可以应用在本类的成员方法
中,也可以应用在本类的构造方法中
(3)this.属性名 : 访问当前对象的属性
this.成员方法名(实参):访问当前对象的成员方法
(4)注意:this.通常可以省略,但是当成员变量和局部变量命名冲突时,要使用this.
来区分成员变量
第二种应用:this()
(1)this():应用在本类的构造方法中,用于调用本类中的其他构造方法
(2)this():调用本类无参数的构造方法
this(实参):调用本类有参数的构造方法
(3)注意:this()/this(实参)的应用必须使用在构造方法中的第一行有效语句
(4)在一个类中,不能所有的构造方法的第一行都使用this()/this(实参);
防止出现构造方法的递归/回环调用
this()的使用不是很频繁,主要靠this.就可以解决
举例说明:
package com;
public class Test{
public static void main(String[] args){
Student s = new Student("姓名",18,99.0);
System.out.println(s.name+"/t"+s.age+"/t"+s.score);
}
}
class Student{
String name;
int age;
double score;
//构造方法
public Student(){}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public Student(String name,int age,double score){
this(name,age);
this.score=score;
}
}