4、构造方法

2021-03-18  本文已影响0人  爱学习的代代

前面我们用到的是实例化一个对象,然后调用类里定义的init()方法,来对成员变量赋值。代码如下:

TestMerchandise.java

      Merchandise m = new Merchandise();
      m.init(1,"牙刷", 200, 5, 2.5);


Merchandise.java
    void init(int id, String name, int count, double soldPrice, double purchasingRrice) {
        this.id = id;
        this.name = name;
        this.count = count;
        this.soldPrice =soldPrice  > 0 ? soldPrice : 0;
        this.purchasingRrice = purchasingRrice;
    }

一、有没有什么方式在对象创建的时候就自动去调用inti方法呢?

有的,这个方式就是构造方法(Constructor)。
代码如下:

TestMerchandiseWithConstructor.java

        MerchandiseWithConstructor c = new MerchandiseWithConstructor(1,"茶杯",11,25,20);



MerchandiseWithConstructor.java

    public MerchandiseWithConstructor(int id, String name, int count, double soldPrice, double purchasingRrice) {
        this.id = id;
        this.name= name;
        this.count = count;
        this.soldPrice = soldPrice;
        this.purchasingRrice = purchasingRrice;
    }

二、关于构造方法的知识点:

  1. 构造方法也是一个方法,需要在类中显示的声明
  2. 构造方法的方法名与类名保持一致
  3. 构造方法无返回值。因为其返回的是实例化对象的一个引用,返回值没有意义。
  4. 当类中没有写构造方法的时候,java会默认添加这样的一个构造方法
    public Merchandise(){}
  5. 构造方法仅可在对象创建(new)的时候使用,不可被.操作符使用。
  6. 构造方法使用时在new一个对象的时候,将属性传递进来即可。
上一篇 下一篇

猜你喜欢

热点阅读