The use of toString() in user defined class

  1. Recall that Java does the following conversion when + is used with a String value:

        String + AnotherType  -->  String + String
        AnotherType + String  -->  String + String
    

    The "other type" can be:

  2. Recall that conversion of user defined classes to String is by done by providing the method

    String toString() { ... }
    inside the class definition ( click here)

  3. What does this mean ???


    Example:
          BankAccount harrysChecking = new BankAccount(1000.0);
    
          System.out.println("Harry's Account: " + harrysChecking);
    			     String          +  BankAccount
    
    Java will evaluate the String + operator as: "Harry's Account: " + harrysChecking.toString()

  4. BankAccount with a toString method:

    class BankAccount { private double balance; public BankAccount() { balance = 0.0; } public BankAccount(double initialBalance) { balance = initialBalance; } public String toString() // will be used by + operator { return("$" + balance); } public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { if ( amount <= balance ) balance = balance - amount; else System.out.println("** Insufficient funds to withdraw $" + amount); } public double getBalance() { return(balance); } }

  5. The bottom line:


    Example continued....:
          BankAccount harrysChecking = new BankAccount(1000.0);
    
          System.out.println("Harry's Account: " + harrysChecking);
    
    Evaluated as:
    
    			 "Harry's Account: " + harrysChecking.toString()
    			 "Harry's Account: " + "$1000"
    			 "Harry's Account: $1000"
     
    
    System.out.println("Harry's Account: " + harrysChecking) prints:
    
    			 "Harry's Account: $1000" 
    

    Java gives the author of the class the complete control on how objects of that classes will be printed !

  6. Demo programs: