Wednesday, January 24, 2007

Lecture 9

Special Functions
  • already we have seen clone()
    • this is a special method that is possessed by all objects
  • we will talk about two more in this lecture
    • toString()
    • equals()
  • returns an object of type String
  • 'cast' your object object to a string type
  • creates a string output of your objects current state
    • contents of all private instance fields
  • very useful for debugging
  • the compiler uses toString() whenever it needs to cast your object to a String

MyObject x = new MyObject();

  • println takes a String argument
  • this is equivalent to saying:
  • System.out.println(x.toString());
  • In a toString method you should do the following
    • include the name of the class
    • include all the private fields
  • if MyObject contains only a private int a
    • toString() output should be
      • MyObject[a=0]
  • returns a boolean
    • true or false
  • checks to see whether two objects are equal
  • returns true if they are equal, false if they are not
The default form of this method is

Public boolean equals(Object, OtherObject)

  • we must use the most general form of the default equals() in order to capture all objects
Public Class MyObject{

private int x;
public boolean equals(Object, OtherObject){
MyObject other = (MyObject)OtherObject;
return (this.x == other.x);

  • if x and y are objects and not primitives then
    • x==y if x and y point to the same object
Delegation within the class
  • Example: code used by many methods in the same class
  • Example: Constructors

1 comment:

george said...

Thank you, your notes are very helpful.
I appreciate that.
I am also wondering if you got this Friday notes; because I missed it.

Thanks in advance.