anne007 发表于 2009-1-14 08:26:53

java中this与super用法

this用法
    this的用法在java中大体可以分为3种:






//1.普通的直接引用
class test {
   private int x,y;
   public test(int x,int y) {
       setX(x);//也可以写为this.setX(x);这种情况下this可以省略.
   }
}
//2.方法中的某个形参名与当前对象的某个成员有相同的名字.为了不混淆,使用this区分有this引用的是成员,没有this是形参
class test {
   private int x,y;
   public test(int x,int y) {
       setX(x);//也可以写为this.setX(x);这种情况下this可以省略.
   }
   setX(int x){
       this.x = x;//this.x是引用的对象,x是setX(int x)中的行参x
   }
}
//3.引用构造函数
class test.{
    public int x,y;
    public test(int x,int y){
      this.x = x;
      this.y = y;
    }
    public test(){
         this.(2,0)//构造函数调用其他构造函数的方法,这个例子调用上面那个复用构造函数的方法
    }
}

    super用法
    super 用在构造函数时要放在第一行,相当于调用super就刷新了构造函数
    super.g() 调用的成员 它引用当前对象的直接父类中的成员(用来访问直接父类中被隐藏的父类中成员数据或函数,基类与派生类中有相同成员定义时)
   
                  
    实例说明
   




package test;
public class ThisTest {
    private int i=0;
    //第一个构造器:有一个int型形参
    ThisTest(int i){
       this.i=i 1;//此时this表示引用成员变量i,而非函数参数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));
       //从两个输出结果充分证明了i和this.i是不一样的!
    }
    //第二个构造器:有一个String型形参
    ThisTest(String s){
       System.out.println("String constructor:" s);
    }
    //第三个构造器:有一个int型形参和一个String型形参
    ThisTest(int i,String s){
       this(s);//this调用第二个构造器
       //this(i);   
       /*此处不能用,因为其他任何方法都不能调用构造器,只有构造方法能调用他。
       但是必须注意:就算是构造方法调用构造器,也必须为于其第一行,构造方法也只能调
       用一个且仅一次构造器!*/
       this.i=i;//this以引用该类的成员变量
       System.out.println("Int constructor:" i " " "String constructor:" s);
    }
    public ThisTest increment(){
       this.i;
       return this;//返回的是当前的对象,该对象属于(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()返回一个在tt0基础上i的ThisTest对象,
       //接着又返回在上面返回的对象基础上i的ThisTest对象!
    }
}
运行结果:
   
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运用在构造函数中
class test1 extend test{
    public test1()...{
         super();//调用父类的构造函数
    }
    public test1(int x){
         super(x);//调用父类的构造函数,因为带形参所以super 也要带行参
    }
}
//2.调用父类中的成员
class test1 extend test{
    public test1(){}
    public f(){//假如父类里有一个成员叫g();
         super.g();//super引用当前对象的直接父类中的成员
    }
}    上一页
页: [1]
查看完整版本: java中this与super用法