Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
class Object
-
Every Java class extends object.
-
Does that mean that you can apply the methods of class Object to any object?
Yes, indeed, it does.
-
Sometimes you may want to override these methods to make them more useful.
-
Object Methods:
-
equals() returns true if the two objects point to the same area
in memory. You may want to override this to return true if the instance
fields of the object are equal. Remember, in a case like String,
you can have two different objects with the same values.
Overriding equals() allows you to make it more useful. Example: object1.equals(object2);
-
toString() By default, Java will return the name of the class
and the value of its instance fields in square brackets. Usually
you will want something more readable. toString() is often used in
System.out.println and the like. Overriding toString is easy.
For example, our Quarters object might override it like so:
public String toString() {
return getClass().getName() + " has the following
due dates: quiz - " + quiz.toString() + " midterm - " + midterm.toString()
+ " projectOne - " + projectOne.toString();
}
-
As you see, you end up with something with more meaning to the user.
-
Any time the + operator is used with a class, toString() is automatically
called. And, the Sytem.out.println() method calls the toString()
method on any object. So, as you can see, this is a very important
method!
-
getClass() returns the class of an object. Pretty simple,
better leave this one alone.
Array Lists



Created by: Brandan
Jones January 4, 2002