構造函數中的super和this的使用

super用於調用父類構造函數的部分,其必須出如今構造函數的第一行。super在調用時第一件事就是去執行父類構造函數的部分,所執行的父類構造函數與super()括號中的參數相對應。函數

this用於在一個構造函數中調用同一個類另外一個構造函數,其也必須是第一行語句。this

super和this不能同時出如今一個構造函數中,其兩個在使用時必須出如今構造函數的第一行語句,其區別爲super調用父類構造函數,this調用自身類的構造函數。spa

爲便於理解,能夠將this理解爲本身,也就是這個類自己,所以調用this是調用本身類的構造函數。code

public abstract class Animal {
    private String name;
    public String getName() {
        return name;
    }
    public Animal() {
        
    }
    public Animal(String theName) {
        name=theName;
    }
    public Animal(String x,String getname) {
        
    }

}
public class Hippo extends Animal{
    String name;
    public Hippo() {    //編寫此構造函數父類需也有無參構造函數
        String test;
    }
    public Hippo(String name) {
        super(name);    //使用super方法將name傳給父類Animal
        System.out.println("big");
    }
    
    public Hippo(String x,String name) {
        this(name);        //this爲調用只有一個string參數的構造函數,即調用上面的構造函數輸出big
        //super(name);    //super和this只能調用一個
        System.out.println(x);
        
    }

}

輸出結果爲blog

big
Buffyip

相關文章
相關標籤/搜索