面向对象-构造方法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)一般从参数少的方法调用参数多的方法(参数的集中处理)看上面的案例。

版权声明:本文为prince77qiqiqq原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。