- 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();
System.out.println(x);
- 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
Public boolean equals(Object, OtherObject)
- we must use the most general form of the default equals() in order to capture all objects
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
- Example: code used by many methods in the same class
- Example: Constructors
1 comment:
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.
Post a Comment