-2
abstract class Library {
  private String day;
  public String getDay()
  {
    return day;
  }
  public void setDay(String oo){
      day = oo;
   }

  public abstract String setDate();
}

class Books extends Library {
  public String setDate() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");

    String dat = this.getDay();
    LocalDate localDate = LocalDate.parse(dat, formatter);

    LocalDate when = localDate.plusDays(7);

    String waitString = when.format(formatter);
    return waitString;
   }
}

class Main {
   public static void main(String[] args) {
   for (int i=0; i<10; i++){
        System.out.println(rent[i].getDay() + rent[i].setDate());
   }
}

Java gives me an Exception in thread "main" java.lang.NullPointerException from String dat = this.getDay();, but when I change it to like String dat = 23-Mar-2019it works fine. It seems like java is not responding to "this.getDay()" from the extended class, but I do not know how to fix this.

Niles
  • 1
  • 1
    `private String day;` - is null unless you give it a value. How does Java know what value you want the String to contain? You have a `setDay(…)` method to set the value of the day. Don't you think you should invoke that method first before you try to get the value? – camickr Jun 12 '20 at 00:52
  • What is `rent`? Please post a [mcve] with a full stack trace. – Sotirios Delimanolis Jun 12 '20 at 02:00

1 Answers1

-1

In Java, instance and class variables are initialized with yours default value. For Objects the default value is null. Then, if you change private String day; to private String day = LocalDate.now().toString(); and import java.time.LocalDate, you will not receive a nullPointerException.

Or you can change your method to:

public String getDay()
 {
     if(day == null) return LocalDate.of(2020, 01, 01).toString();
     else return day;
 }