this
與super
都是一個表示對象的引用.
區別在于this
是指向調用這個方法的對象,而super
指向調用這個方法的父對象.
下面寫一個栗子: (注意注釋位置)
class Car{
public int tires; //輪胎
public Car(int tires){
this.tires=tires; //將形參tires賦值給當前對象的tires成員
}
public void start(){
System.out.println("啟動~");
}
}
class Benz extends Car{
static String brand="Benz";
private String color;
public Benz(int tires,String color){
super(tires); //子類調用父類構造函數,必須放在第一行
this.color=color;
}
public void setColor(String color){
this.color=color; //將形參color賦值給當前對象的color成員
}
public void run(){
super.start(); //子類調用父類方法,行車前先啟動
System.out.println("Run~~~~");
}
}
class CarDemo{
public static void main(String[] args){
Benz benz = new Benz(4,"red");
benz.run();
}
}
結果:
啟動~
Run~~~~
this
與super
都可以用于調用當前類/父類方法,也可以用于調用構造方法,不過要放在方法的第一行