super和this
Posted on 2010-08-09 10:22 帥子 閱讀(235) 評論(0) 編輯 收藏 所屬分類: j2se技術(shù)專區(qū) 、j2ee技術(shù)專區(qū)public class ThisTest {
private int i=0;
//第一個(gè)構(gòu)造器:有一個(gè)int型形參
ThisTest(int i){
this.i=i+1;//此時(shí)this表示引用成員變量i,而非函數(shù)參數(shù)i
System.out.println("Int constructor i——this.i:? "+i+"——"+this.i);
System.out.println("i-1:"+(i-1)+"this.i+1:"+(this.i+1));
//從兩個(gè)輸出結(jié)果充分證明了i和this.i是不一樣的!
}
//? 第二個(gè)構(gòu)造器:有一個(gè)String型形參
ThisTest(String s){
System.out.println("String constructor:? "+s);
}
//? 第三個(gè)構(gòu)造器:有一個(gè)int型形參和一個(gè)String型形參
ThisTest(int i,String s){
this(s);//this調(diào)用第二個(gè)構(gòu)造器
//this(i);
/*此處不能用,因?yàn)槠渌魏畏椒ǘ疾荒苷{(diào)用構(gòu)造器,只有構(gòu)造方法能調(diào)用他。
但是必須注意:就算是構(gòu)造方法調(diào)用構(gòu)造器,也必須為于其第一行,構(gòu)造方法也只能調(diào)
用一個(gè)且僅一次構(gòu)造器!*/
this.i=i++;//this以引用該類的成員變量
System.out.println("Int constructor:? "+i+" "+"String constructor:? "+s);
}
public ThisTest increment(){
this.i++;
return this;//返回的是當(dāng)前的對象,該對象屬于(ThisTest)
}
public static void main(String[] args){
ThisTest tt0=new ThisTest(10);
ThisTest tt1=new ThisTest("ok");
ThisTest tt2=new ThisTest(20,"ok again!");
System.out.println(tt0.increment().increment().increment().i);
//tt0.increment()返回一個(gè)在tt0基礎(chǔ)上i++的ThisTest對象,
//接著又返回在上面返回的對象基礎(chǔ)上i++的ThisTest對象!
}
}
運(yùn)行結(jié)果:
Int constructor i——this.i:? 10——11
String constructor:? ok
String constructor:? ok again!
Int constructor:? 21
String constructor:? ok again!
14
注意:this不能用在static方法中!所以甚至有人給static方法的定義就是:沒有this的方法!雖然夸張,但是卻充分說明this不能在static方法中使用!
//1.super運(yùn)用在構(gòu)造函數(shù)中
class test1 extend test{
public test1()...{
super();//調(diào)用父類的構(gòu)造函數(shù)
}
public test1(int x){
super(x);//調(diào)用父類的構(gòu)造函數(shù),因?yàn)閹螀⑺詓uper 也要帶行參
}
}
//2.調(diào)用父類中的成員
class test1 extend test{
public test1(){}
public f(){//假如父類里有一個(gè)成員叫g(shù)();
super.g();//super引用當(dāng)前對象的直接父類中的成員
}
}