类的成员之三:构造器

一、构造器的特征
它具有与类相同的名称
它不声明返回值类型。(与声明为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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值