moocNotes-Java object-oriented programming(constructor)

package javaObjectOrientedProgrammingMooc;

public class Car {
    private String band;
    private String color;
    Car(){
        band = "Test";
        color = "grey";
    }
    Car(String bandIn, String colorIn){
        band = bandIn;
        color = colorIn;
    }
    public String getBand() {
        return band;
    }
    public String getColor() {
        return color;
    }
}

In the code given above, we can find there are two special function: Car() and Car(String bandIn, String colorIn), which have the same name with class and don't have return value, we call this function as constructor.

Why we need constructor?

When we create an object, we need to assign an initialization to attribute of object, which ensure it's meaningful of an object, so the best time of initialization is when create an object, so,The function of constructor is to initialize the member variable.

  1. The statement of constructing an object is:ClassName objectName = New ClassName();So, util now, we have known the function after the key word new is constructor.

  1. When the constructor don't have parameter, the java VM will give the defaut value to variables, otherwise, use the parameter in constructor.

Summary:

  1. The name of constructor and class is totally same.

  1. Constructor does't have return value, so we cannot add void to modifier. Also, cannot use return modifier.

  1. The main function of constructor is to initialize variable.

  1. The constructor will be called by system automatically when the object created.

  1. If we define constructor, it will use the constructor we defined, Java VM will not define a default constructor.

  1. If we don't define constructor, the Java VM will generate a default constructor, which has the same name with class and with default value.

  1. The constructor only can be called once.

package javaObjectOrientedProgrammingMooc;

public class testStudent {
    public static void main(String[] args) {
        
        Student peter = new Student();
        peter.print();   // default value
        
        peter.setSno("007");
        peter.setSname("Leo");
        peter.print();
        
        Student james = new Student("002");
        james.print();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值