-1

I'm still somewhat new to Java and OOP and I'm having trouble printing the return value of the toString method I created.

I have the public class Account:


public class Account {
    
    double currentBalance;
    
    Account(double currentBalance){
        this.currentBalance = currentBalance; 
    }
    
    double getBalance() {
        return(this.currentBalance);
    
    }
    
     void deposit(double ammount) {
        
        this.currentBalance += ammount;
        
    }
     void withdraw(double ammount) {
        this.currentBalance -= ammount;
    }
    
    public String toString() {
        return("Your current account balance is: " + this.currentBalance);
        
    }
    
}
        
    
public class AccountTester {

    public static void main(String[] args) {
        
        
        System.out.println("Welcome to the BANK");
        
        Account[] acc = new Account[10];
        
        
        acc[0] = new Account (100000); //initial ammount of 100k
        System.out.println("Your current total balance is: " + "$"+ acc[0].getBalance());
        
        acc[0].deposit(50000); //deposit 50k
        System.out.println("Current total balance after depositing is: " + "$" + acc[0].getBalance());
        
        acc[0].withdraw(10000);
        System.out.println("Current total balance after withdrawing is: " + "$" + acc[0].getBalance());
        
        
        System.out.println("CHECKING ACCOUNT");
        acc[1] = new CheckingAccount(10000,50000); //overdraft limit of 1000, initial amount of 50k
        System.out.println();
        
        System.out.println(Account.toString());
    }

}

I get the message "Cannot make a static reference to the non-static method toString from the type account.

  • 1
    You're calling toString() as if it was a static method of the class Account, but it is instead an instance method. So you should do it with `acc[0].toString()` – Matteo NNZ May 10 '22 at 07:57
  • 1
    Well which account do you expect to get the result for? What would you expect to happen if you hadn't created *any* instances of `Account`, but called `Account.toString()`? `toString` is an instance method, which means you need to call it *on a specific instance*, e.g. `System.out.println(acc[0].toString())` – Jon Skeet May 10 '22 at 07:58

0 Answers0