1

An error occurred when try to use the override toString method

public class Test {
public static void main(String args[]) {
    Account a = new CheckingAccount(1, 100, 0.1, 200);
    System.out.println(a.toString());
}
}

class Account {
int id;
double balance;
double annuallntegerRate;
Date dateCreated;

public Account() {
};

public Account(int id, double balance, double annuallntegerRate) {
    this.id = id;
    this.balance = balance;
    this.annuallntegerRate = annuallntegerRate;
    Date dateCreated = new Date();
}

public void setRate(double annuallntegerRate) {
    this.annuallntegerRate = annuallntegerRate;
}

public double getRate() {
    return annuallntegerRate;
}

public double getBalance() {
    return balance;
}

public void withDraw(double change) {
    balance -= change;
}

public void deposit(double change) {
    balance += change;
}

@Override
public String toString() {
    return "id: " + id + "balance:" + balance + "annuallntegerRate:" + 
annuallntegerRate + "date:"
            + dateCreated.toString();
}
}   

class CheckingAccount extends Account {
double limit;

public CheckingAccount(int id, double balance, double annuallntegerRate, 
double limit) {
    this.id = id;
    this.balance = balance;
    this.annuallntegerRate = annuallntegerRate;
    this.limit = limit;
    Date dateCreated = new Date();
}

public void setLimit(double limit) {
    this.limit = limit;
}

public double getLimit() {
    return limit;
}

@Override
public void withDraw(double change) {
    balance -= change;
}

@Override
public String toString() {
    return "id: " + id + "balance:" + balance + "annuallntegerRate:" + 
annuallntegerRate + "date:"
            + dateCreated.toString() + "limit:" + limit;
}
}

I want to override the Object's toString method. It seems a doesn't exist

Exception in thread "main" java.lang.NullPointerException at test.CheckingAccount.toString(Test.java:82) at test.Test.main(Test.java:8)
JeremyP
  • 84,577
  • 15
  • 123
  • 161
soullll
  • 11
  • 1
  • this has nothing at all to do with @Override. probably, your dateCreated is not instantiated. – Stultuske Oct 11 '19 at 09:00
  • 1
    Consider replacing `Date dateCreated = new Date()` with simply `dateCreated = new Date()`, you are currently using a variable local to the constructor . – Arnaud Oct 11 '19 at 09:02
  • replace `Date dateCreated = new Date();` with `this.dateCreated = new Date();` – lczapski Oct 11 '19 at 09:02
  • You're creating a local version of dateCreated that shadows your field. – matt Oct 11 '19 at 09:59

0 Answers0