面向對象-構造方法2-構造方法中調用另一個重載構造方法

承接面向對象-構造方法1
如何在構造方法中調用另一個重載的構造方法:

案例:

  • 編寫汽車類
  • 汽車類屬性:
    int id;
    String brand;
    String color;
    int weight;
  • 汽車類中的構造方法:
    Car();
    Car(id,brand);
    Car(id,brand,color);
    Car(id,brand,color,weight);
  • 汽車類中的方法
    go();
    stop();
    turnLeft();
    turnRight();

public class Car {
    int id;
    String brand;
    String color;
    int weight;

    public Car() {
    }
    public Car(int id,String brand){
        this(id, brand, null);
    }
    //(2)在構造方法中做調用,調用另一個重載的構造方法,讓重複的代碼只寫一次,也便於以後的時候修改變量。
    public Car(int id,String brand,String color){

        //this.id = id;
        //this.brand = brand;
        //this.color = color;
        //重複的代碼只寫一次做調用
        //一個構造方法,調用另一個重載的構造方法
        this(id, brand, color, 0);//0位重量的默認值
    }

    //(1)我們在構造方法中集中的處理所有參數
    public Car(int id,String brand,String color,int weight){
        this.id = id;
        this.brand = brand;
        this.color = color;
        this.weight = weight;
    }

    public void go(){
        System.out.println(
            id+"號"+color+"的汽車啓動");
    }
    public void stop(){
        System.out.println(
            id+"號"+color+"的汽車停止");
    }
    public void turnLeft(){
        System.out.println(
            id+"號"+color+"的汽車左轉");
    }
    public void turnRight(){
        System.out.println(
            id+"號"+color+"的汽車右轉");
    }
}

測試類:


public class Test1 {
    public static void main(String[] args) {
        Car c1 = new Car();
        Car c2 = new Car(1,"夏利");
        Car c3 = new Car(2,"奧拓","土豪金");
        Car c4 = new Car(3,"金盃","紅色",1000);

        c1.go();
        c2.go();
        c3.go();
        c4.go();
        c1.turnLeft();
        c2.turnRight();
        c3.stop();
        c4.stop();
    }
}

this

  • 引用
    保存當前對象的內存地址,用this可以調用當前對象的成員。
    this.xxxx;
    this.xxx();
  • 構造方法間調用
    在一個構造方法的中,調用另一個重載的構造方法。
    this(參數…..);
    目的:
    (1)減少代碼重複
    (2)一般從參數少的方法調用參數多的方法(參數的集中處理)看上面的案例。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章