Object - The Parent Class of All and Every Java Class
The object class in Java is
the parent class of all classes.
Everything is an object. Everything is derived from an object.
All classes automatically inherit the object class and public methods that
are in it.
Methods that are in the Object class and that all other classes
automatically
inherit are:
public boolean equals(Object obj)
//by default it check to see if two object share the same memory
address
//are they aliases of each other
//the String class, for example, overrides the normal behavior of
the equals //method and checks to see if the characters in both
strings are the same
//-> Here is an example of how to write assuming a Car class and a
method
//-> in Car class called getHP which returns an int and a int in the
//-> Car class called hp, also have a String called name and a
method called
//-> getName() which returns a String
public boolean equals (Object obj) { //the header is always same for
all classes
Car c = (Car) obj; //always must cat the obj parameter to
object working with
if ((hp == c.getHP()) && (name.equals(c.getName()))
return true;
return false;
}
public String toString()
//by default the toString method is invoked when you ask
System.out.print or
//System.out.println to print out an object reference
//default behavior is to print out the memory address of the object
//to use make sure you return a String, here is an example assuming
a class
//called Car with a data String in class called name.
public String toString() {
String hold;
hold="My car is a: " + name;
return hold;
} |