toString method

Any time that you need a string representation of an object, we use toString.


// jamesprogram.java
class jamesprogram {

public static void main (String[] args){

cat catObject = new cat(5,6,7);

}
}


//cat.java
public class cat {

// 3 private variables
private int month;
private int day;
private int year;

// constructor
public cat(int m, int d, int y){
month=m;
day=d;
year=y;

// the reference 'this' below is a reference
// to whatever object we just built
System.out.printf("The contructor for this is %s\n", this);
}

public String toString(){
return String.format("%d/%d/%d", month, day, year);
}

}

Outputs:

The contructor for this is 5/6/7

Since ‘this’ is used, in the system.out.printf statement, it goes to look for the toString method, and returns this.

Leave a Reply