在開始本文之前,先寫以下代碼的輸出:
public class Flower{
int petalCount = 0;
String s = "init value";
Flower(int petals){
petalCount = petals;
print("Constructor int arg only,petalCount = " + petalCount);
}
Flower(String s){
print("Constructor string arg only,ss = " + s);
this.s = s;
}
Flower(int petals,String s){
this(petals);
this.s = s;
print("String & int args");
}
Flower(){
this(47,"hi");
print("default constructors ,no args");
}
void flowerPrint(){
print("petalCount = "+petalCount+",s = " + s);
}
void print(String s){
System.out.printf(s);
}
public static void main(String[] args){
Flower flower = new Flower();
flower.flowerPrint();
}
}
(參考:Thinking in Java ,page86。)
如果有疑問,那么我復(fù)述一下通過this關(guān)鍵字實(shí)現(xiàn)構(gòu)造器調(diào)用構(gòu)造器的規(guī)則:
1、用this調(diào)用其他構(gòu)造器時(shí),僅能調(diào)用一個(gè);
2、構(gòu)造器僅能置于被調(diào)用構(gòu)造器的入口處,否則編譯器報(bào)錯(cuò);
3、不能在非構(gòu)造器中調(diào)用構(gòu)造器;
其中規(guī)則2可以解釋規(guī)則1(對(duì)于規(guī)則2的報(bào)錯(cuò)原因以及規(guī)則3的原因,待查)。
this:通常指這個(gè)對(duì)象或者當(dāng)前對(duì)象,該關(guān)鍵字表示對(duì)當(dāng)前對(duì)象的引用。
如果能理解上面這句話,那么對(duì)于static關(guān)鍵字的理解加深:static方法就是沒有this的方法。
原因:static方法可以理解為類方法。而this方法的含義則是一個(gè)實(shí)例類的方法的引用,與static方法的含義沖突,如果采用this方法的形式進(jìn)行調(diào)用,那么此時(shí)如何知道該this的static方法是屬于哪一個(gè)實(shí)例呢?(有點(diǎn)繞口)
以上demo的輸出我相信能理解以上意思的,都可以寫出:
Constructor int arg only,petalCount = 47
String & int args
default constructors ,no args
petalCount = 47,s = hi
看了上面的例子,對(duì)this關(guān)鍵字有了初步的認(rèn)識(shí)。
1、將方法入?yún)①x給當(dāng)前對(duì)象實(shí)例的成員變量
public class Demo{
private String username;
private String password;
private void setUsername(String username){
this.username = username;
}
}
如果熟悉javaweb開發(fā)的都知道,其實(shí)這個(gè)setUsername方法就是由ide自動(dòng)生成的set/get方法之一。
2、將對(duì)象實(shí)例自身作為參數(shù)傳遞給方法
public class HelloA {
public static void main(String[] args) {
A aaa = new A();
aaa.print();
B bbb = new B(aaa);
bbb.print();
}
class A {
public A() {
// 調(diào)用B的方法
new B(this).print();
}
public void print() {
System.out.println("HelloAA from A!");
}
}
class B {
A a;
public B(A a) {
this.a = a;
}
public void print() {
//調(diào)用A的方法
a.print();
System.out.println("HelloAB from B!");
}
}
}
3、調(diào)用類內(nèi)的其他構(gòu)造函數(shù)
這種用法針對(duì)擁有多個(gè)成員變量可以使用,對(duì)不定參數(shù)也可采用類似方法。
public class Demo{
private String userName;
private String password;
private String nickName;
public Demo(){
}
public Demo(String userName){
this.userName = userName;
}
public Demo(String userName,String password){
this(userName);
this.password = password;
}
public Demo(String userName,String password,String nickName){
this(userName,password);
this.nickName = nickName;
}
}
4、其他
當(dāng)然了,還有其他用法,用的不多,就不列舉了。
最后,再提一下與this關(guān)鍵字類似的一個(gè)關(guān)鍵字,super。super的作用則是調(diào)用父類(也稱為基類)的方法或者構(gòu)造參數(shù)等,這個(gè)也比較常見??梢哉艺蚁嚓P(guān)資料,了解一下。