Java中为什么需要空的构造函数

package com.haloasis.Abstract;

public class Circle extends Shape{

    private Integer r;

    public Circle(Integer r) {
        this.r = r;
    }

    public Circle() {

    }

    public Integer getR() {
        return r;
    }

    public void setR(Integer r) {
        this.r = r;
    }

    @Override
    public Double area() {
        return Math.PI * Math.pow(r, 2);
    }
}

这个类中有了带参的构造函数还有一个空的构造函数。

因为如果写了一个带参的构造函数,Java就会将该构造函数替换掉默认的空构造函数,使得以下代码报错。

Shape circle = new Circle();

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.