当参数构造函数失败时,如何确保不调用默认构造函数?

时间:2013-03-29 23:49:08

标签: java exception constructor

这是代码。我必须使用Date Class并将其扩展为创建ExtendedDate。无论如何我不应该更改Date类。我非常感谢您提供的任何帮助。我对如何解决这个问题一无所知

public static void main(String[] args) {
    /* Trying to create a date with month = 3, date = 40, year = 2010. Objective to is throw an error/exception - "Date can't be created" */   
    ExtendedDate Dt1 = new ExtendedDate(03,40,2010);
    System.out.println(Dt1.getDay()); 
    //I don't want this statement to be executed because 40 is not valid. But it's printing "1" which is the default value for the default constructor
}

class ExtendedDate extends Date {
    // Default constructor
    // Data members are set according to super's defaults
    ExtendedDate() {
        super();
    }

    // Constructor that accepts parameters
    public ExtendedDate(int month, int day, int year)  {
        setDate(month, day, year);
    }

    @Override
    public void setDate(int monthInt, int dayInt, int yearInt) {
        if (isValidDate(monthInt, dayInt, yearInt)) 
        //isValidDate code is working perfectly fine.
        {
            super.setDate(monthInt, dayInt, yearInt);
        }
        else {
            System.out.println("Wrong Date");
        } 
    }

HERE是日期类

public class Date {

    private int month; // instance variable for value of the date’s month

    private int day; // instance variable for value of the date’s day

    private int year; // instance variable for the value of the dates

    // Default constructor: set the instance variables to default values: month = 1; day = 1; year = 1900;
    public Date() {
        month = 1;
        day = 1;
        year = 1900;
    }

    // Constructor to set the date
    // The instance variables month, day, and year are set according to received parameters.

    public Date(int month, int day, int year) {
        this.month = month;
        this.day = day;
        this.year = year;
    }

    public void setDate(int month, int day, int year)
    {
        this.month = month;
        this.day = day;
        this.year = year;
    }

    public int getMonth()
    {
        return month;
    }

    public int getDay() {
        return day;
    }

    public int getYear() {
        return year;
    }

1 个答案:

答案 0 :(得分:3)

当某个参数无效时,您应抛出IllegalArgumentException:

@Override
public void setDate(int month, int day, int year) {
    if (isValidDate(month, day, year)) {
        super.setDate(month, day, year);
    }
    else {
        throw new IllegalArgumentException("Invalid date");
    } 
}

详细了解the Java tutorial中的例外情况。

请注意,从构造函数调用可覆盖的方法是一种不好的做法。您应该直接从构造函数调用isValidDate()(假设此方法是私有或最终的)。