java-this,this()的应用

1.this:调用本类的成员变量(不是局部变量)

public class TestStudent{
	public static void main(String[] args) {
		Student s = new Student("张1",35,94.2);
		System.out.println("name="+s.name+"-age="+s.age+"-score="+s.score);
	}
}

class Student {

	String name;
	int age;
	double score=3.2;
	
	public Student() {
		System.out.println("Student()...");
	}
	public Student(String name, int age) {
		System.out.println("Student(String name, int age)...");
	}
	public Student(String name, int age, double score) {
        this.name = name;
		this.age = age;
		this.score = score;
		System.out.println("Student(String name, int age, double score)...");
	}
}

这个里面的this表示成员变量,this.name表示成员变量name,

2.this()/this(实参):调用本类的构造方法。

public class TestStudent{
	public static void main(String[] args) {
		Student s = new Student("张1",35,94.2);
		System.out.println("name="+s.name+"-age="+s.age+"-score="+s.score);
	}
}

class Student {

	String name;
	int age;
	double score=3.2;
	
	public Student() {
		System.out.println("Student()...");
	}
	public Student(String name, int age) {
                this.name = name;
		this.age = age;
		System.out.println("Student(String name, int age)...");
	}
	public Student(String name, int age, double score) {
                this(name,age);
		this.score = score;
		System.out.println("Student(String name, int age, double score)...");
	}
}

在创建对象时,new分配空间,赋默认值,执行三个参数的构造方法,此时,jvm不将属性初始化的操作移交给此构造方法,而是 执行this(name,age)(当有这个时,把再将属性初始化移交给此构造方法),去两个参数的构造方法,然后进行属性初始化,再执行构造方法中的原有内容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章