-1

I have a class like this:

public class DateS extends Date {
    public DateS yesterday(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(this);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        return (DateS) cal.getTime();
    }
}

It can be successfully built. At runtime, when I call date.yesterday(), a Cannot cast 'java.util.Date' to 'myproject.package.DateS' are throwed.

I need to know why and what can I do to fix this.

jhpg
  • 397
  • 3
  • 9
  • Well, `Calendar.getTime()` doesn't return an instance of `myproject.package.DateS`, so you can't do that cast. To fix it, you can just return a `Date`, rather than a `DateS`. – Andy Turner Sep 19 '16 at 21:20
  • On Swift when you create a extension of a class you can add functionalities to them. What is equivalent in Java? How can I add new attributes and methods to Date class directly? – jhpg Sep 19 '16 at 22:00
  • 2
    @JorgeHenrique there is no equivalent to that in java. You will probably need to wrap the returned `Date` in your `DateS` class. then you can delegate and also add additional functionality. – Neil Locketz Sep 20 '16 at 02:23
  • 1
    By the way, in java.time, get *yesterday* more simply: `LocalDate.now( ZoneId.of( "America/Montreal" ) ).minusDays( 1 )` – Basil Bourque Sep 20 '16 at 02:59

1 Answers1

3

Because Calendar does not make a DateS it uses a different implementation of Date.

In order to cast to a DateS the object has to be an instance of DateS or a child of that class. Since Calendar doesn't return an instance of DateS you can't cast it. It compiles just fine because theoretically it could work if the returned date was of the correct type, and the compiler can't tell.

Neil Locketz
  • 4,228
  • 1
  • 23
  • 34