2015年12月2日 星期三

this、super

this通常指”當前類別”super通常指”父類別”


參考資料:

 - EX1:

 this 用法:
在你的方法中的某个變數名与当前对象的某个成员有相同的名字,这时为了不至于混淆,你便需要明确使用this关键字来指明你要使用某个成员,使用方法是“this.成员名”,而不带this的那个便是前對象變數
輸出結果
DemoSuper:
Name=kevin Age=22
 public class DemoThis// 紅字為同一個類別的變數
        private String name// 共用暫存變數
        private int age;
        DemoThis(String nameint age){
             setName(name); //你可以加上this来调用方法,像这                                样:this.setName(name);但这并不是必须的
        setAge(age);
        this.print(); // 可以用 print() 取代
        }
        public void setName(String name){
            this.name=name;//此处必须指明你要引用成员变量
        }
        public void setAge(int age){
            this.age=age;
        }
        public void print(){
            System.out.println("Name="+name+" Age="+age);//在此行中并                        不需要用this,因为没有会导致混淆的东西
        }
        public static void main(String[] args){
            DemoThis dt=new DemoThis("Kevin","22");
        }
}


 - EX2:

 this , super用法:
輸出結果:
A Person.
chinese.
A person name is:kevin
his name is:kevin
A person name is:kevin
his name is:kevin
his age is:22

 父類別:Person
            class Person{
 
         public static void prt(String s){              System.out.println(s);          }
          Person(){               prt("A Person.");          }
          Person(String name){                prt("A person name is:"+name);          }
}
 類別
public class Chinese extends Person{
 
 Chinese(){    super(); //调用父类构造函数(1    prt(“A chinese.”); // 繼承Person使用prt()
  }
  Chinese(String name){
    super(name);//调用父类具有相同形参的构造函数(2    prt(“his name is:”+name);  }
  Chinese(String name,int age){    this(name);//调用当前具有相同形参的构造函数(3    prt("his age is:"+age);  }

public static void main(String[] args){  Chinese cn=new Chinese();  cn=new Chinese("kevin");  cn=new Chinese("kevin",22);  }
}

沒有留言:

張貼留言