类的成员之三:构造器

来源:互联网 发布:淘宝商家退款流程 编辑:程序博客网 时间:2024/06/06 12:42

一、构造器的特征
它具有与类相同的名称
它不声明返回值类型。(与声明为void不同)
不能被static、final、synchronized、abstract、native修饰
不能有return 返回值;语句,return ;可以有

二、构造器的作用:
与new一起使用创建对象
给对象的属性进行初始化

三、语法格式
这里写图片描述

public class TestConstructor {    public static void main(String[] args) {        Car car = new Car("宝马","白色");        System.out.println(car.getName()+","+car.getColor());    }}class Car {    private String name;    private String color;    public Car(String name, String color) {        //初始化        this.name = name;        this.color = color;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getColor() {        return color;    }    public void setColor(String color) {        this.color = color;    }}

四、构造器
这里写图片描述
五、构造器的重载
构造器重载使得对象的创建更加灵活,方便创建各种不同的对象。
构造器重载,参数列表必须不同

class Car {    private String name;    private String color;    //构造器的重载    public Car(){    }    public Car(String name){        this.name = name;    }    public Car(String name, String color) {        //初始化        this.name = name;        this.color = color;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getColor() {        return color;    }    public void setColor(String color) {        this.color = color;    }}

六、this调用类的构造器
this可以作为一个类中,构造方法相互调用的特殊格式

class Car {    private String name;    private String color;    //构造器的重载    public Car(){    }    public Car(String name){        this();//调用本类的无参构造        this.name = name;    }    public Car(String name, String color) {        this(name);//调用本类的一个有参构造        this.color = color;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getColor() {        return color;    }    public void setColor(String color) {        this.color = color;    }}

注意:
1.使用this()必须放在构造器的首行!
2.使用this调用本类中其他的构造方法,至少有一个构造方法是不用this的。

0 0
原创粉丝点击