2013-03-29 35 views
-1

這是代碼。我必須使用Date類並將其擴展爲創建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"); 
     } 
    } 

這裏是Date類

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; 
    } 
+0

如果構造函數失敗,則不會更改任何內容,'因爲對象創建本身失敗。 – srkavin

回答

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()(假設此方法是私有的或最終的)。

+0

謝謝了一噸JB。我遵循你的建議,它的工作。你太棒了 :) – user2225994