User:Billyhenderson123/sandbox

The toString method The toString method is a method that is used to get the String representation of an object. If you don't put a toString method into your class, the toString method inherited from java.lang.Object (the cosmic superclass that all Java classes inherit from) will be used. To see this, let's create a driver class to test our Cat class.

A driver class is just an application class that is used to test a storage class. Since we want to test the Cat class, we can call this driver class the TestCat class. Here is the file "TestCat.java":

class TestCat { public static void main(String[] args) { Cat myData = new Cat("Getoff",        5,20,30,10); System.out.println(myData); } } The TestCat class is an application class, so it has a main method. Lines 3 and 4 call the constructor for the Cat class. The constructor requires that three arguments be passed: a String (for the command), and a double (for the number of times the cat is told to get off the counter). So, we are constructing a Cat object that has the command set to "Getoff" and an amount of times the cat is told to get off the counter (5 times the first time, 20 times the second time, 30 times the third time, and 10 times the forth time).

Line 5 prints out the Cat object. Whenever you print out an object, Java uses the toString method to get a String representation of that object. If you don't define a toString method for your class, the toString method inherited from java.lang.Object is used. The toString method from java.lang.Object makes a String that consists of the name of the class concatenated with the "@" character, concatenated with a hex number that is related to the location in memory for that object.