Transcript final

CS2200 Software Development
Lecture: Object class
A. O’Riordan, 2008
this Revisited
• this is Java keyword that allows an object to refer to itself or pass
its own reference to a method
– self-reference used in many OO programming languages—called this in
C++, Java, C#; self in Smalltalk and Python
• For example, in bank account example given previously, a Customer
object could have references to two different accounts. We would
also like Account objects to have references back to Customer.
• Java will interpret this as referring to whichever object is using the
keyword, and create the appropriate reference
• For example, to print out a string representation of the object:
System.out.println(this)
super
• if method overrides one of its superclass's methods, you can invoke
the overridden method through use of the keyword super, e.g.
Superclass and Subclass that overrides printMethod():
public class Superclass: public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass."); }
}…
public class Subclass extends Superclass {
public void printMethod() { //overrides printMethod
super.printMethod();
System.out.println("Printed in Subclass");
}…
• to refer to printMethod() inherited from Superclass, Subclass must
use a qualified name, using super as shown
null
• What happens when we have created an object reference, but we
have not yet assigned an object to it?
• Java has a special object called null, which should be interpreted
as meaning "no object".
• We can assign null to a reference to make it clear that the reference
is not pointing to any object.
• If you execute x.doSomething() and x is null, you will raise a
java.lang.NullPointerException
• Often used in tests: if ( x != null ) x.doSomething();
Class called Object
• Object class, defined in the java.lang package, defines and
implements behaviour common to all classes—including the ones
that you write
• Classes can be derived directly from Object or derived from
classes derived from Object, etc.
• Every class you use or write inherits the instance methods of
Object
• you may need to override them with code that is specific to your
class
• API: http://java.sun.com/javase/6/docs/api/java/lang/Object.html
Methods of Object
•
Object clone() - creates and returns a copy of this object
•
boolean equals(Object obj) - indicates whether some other object is
•
void finalize() - called by the garbage collector on an object when no
“equal” to this one
more references to the object
•
final Class getClass() - returns the runtime class of an object
•
int hashCode() - returns a hash code value for the object
•
String toString() - returns a string representation of the object
•
The notify, notifyAll, and wait methods of Object all play a part in
synchronizing the activities of independently running threads in a program
toString()
• Object's toString() method returns a String representation of the
object, which is very useful for debugging/logging
• The String representation for an object depends entirely on the
object, which is why you need to override toString() in your
classes, e.g.
public class Account {
public String toString () {
return (accNo + "\t" + name + "\t" + bal));
}…
• Object’s implementation returns getClass().getName() + '@' +
Integer.toHexString(hashCode())
equals()
• equals() method compares two objects for equality and returns
true if they are equal
• equals() method provided in the Object class uses the identity
operator (==)—for primitive data types this is okay
• For objects, however the equals() method provided by Object tests
whether the object references are equal—not objects themselves
• Therefore need to override equals()
• Here is an example of a Book class that overrides equals():
public class Book {
public boolean equals(Object obj) {
if (obj instanceof Book)
return ISBN.equals((Book)obj.getISBN());
else return false;
} …
clone()
• Object's implementation of this method checks to see whether the
object on which clone() was invoked implements the Cloneable
interface. If the object does not, the method throws a
CloneNotSupportedException exception
• clone() must be declared as
protected Object clone() throws CloneNotSupportedException
or
public Object clone() throws CloneNotSupportedException
• The simplest way to make your class cloneable is to add implements
Cloneable to your class's declaration. then your objects can invoke
the clone() method
Cloning Arrays
if we want to create a copy of an object or an array, we should specify a
clone() method, which explicitly creates the new structures
public class Bank {
private Account[] list;
public Account[] cloneAccs(){
Account[] clone = new Account[list.length];
for (int i = 0; i<list.length; i++)
clone[i] = list[i];
Note: clones the array,
return clone;
not the objects
}…
Pitfall
Common pitfall of using an array of object references is assuming
that each reference actually points to an object
for (int i = 0; i < list.length; i++)
output += list[i].toString() + "\n";
Fails at runtime if one of the cells contains null
If it is possible that a reference is null, you must test it:
for (int i = 0; i < list.length; i++)
if (list[i] != null)
output += list[i].toString() + "\n";
instanceof
• Test the type of a particular object using the instanceof operator
• if (objectA instanceof ClassB) will yield true if objectA can
be upcast to objectB
• This can save you from a runtime error owing to an improper cast
• For example:
if (obj instanceof MountainBike)
MountainBike myBike = (MountainBike)obj;
• Method overriding preferable for efficiency reasons
getClass()
• getClass() method returns a Class object, which has methods
you can use to get information about the class, such as its name
(getSimpleName()), its superclass (getSuperclass()), and the
interfaces it implements (getInterfaces())
• getClass() has lots of methods (outside scope of this course) –
see API http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html
• For example, the following method gets and displays the class name
of an object:
void printClassName(Object obj) {
System.out.println("The object's class is "
obj.getClass().getSimpleName());
}
• You cannot override getClass()
finalize() and hashcode()
• Object's implementation of finalize() does nothing—you can
override finalize() to do cleanup, such as freeing resources.
• The finalize() method may be called automatically by the
system, but when it is called, or even if it is called, is uncertain.
Therefore, you should not rely on this method
• The value returned by hashCode() is the object's hash code, which
is the object's memory address in hexadecimal. By definition, if two
objects are equal, their hash code must also be equal.
• Note: if you override the equals() method, you change the way
two objects are equated and Object's implementation of
hashCode() is no longer valid