Most Java Classes commonly come with certain methods that makes programming easier. Most of these methods are actually found as methods in Java’s Object class, which all classes inherit from. We’ll call them standard methods, but note that this is all subjective.
equals()
public boolean equals(<ClassName> objToCompare) {
return <boolean expression>;
}
An instance method that checks for equality (read this, trust me) with another Object of the same type/class.
The default equals()
method behaves the same as ==
, i.e. it checks for identity. This is why in most cases we like to override it (which happens whenever we create a method called equals()
)
Generally it involves checking the equality of some attributes of the instances, which is user-defined. For example:
public class Square {
public int sideLength;
public Square(sideLength) //Constructor
{
this.sideLength = sideLength;
}
//equals defined when side lengths are the same
public boolean equals(Square other)
{
return other.sideLength == this.sideLength;
}
}
---
//Assuming we have a square class which constructs with n side length
Square sq1 = new Square(10)
Square sq2 = new Square(10)
System.out.println(sq1 == sq2) //Returns false, see [](Identity%20&%20Equality.md#Identity)
System.out.println(sq1.equals(sq2)) //Returns true
compareTo()
A version of equals()
that also ‘compares’ to data types, to enforce the idea that one instance is ‘greater than’ or ‘lesser than’#todo
toString()
The toString
method which returns a String representation of an object is the way to go. It is automatically called when the object is asked to act like a String, such as when printing an object using System.out.println(obj)
Back to our square class example:
public class Square {
//Previous code...
public String toString()
{
return "Square with side length = " + this.sideLength;
}
}
---
System.out.println(new Square(10)); //prints "Square with side length = 10"
clone()
Does exactly what the name suggests, returns a clone of the object that calls it. Specifically, it returns a unique, separate object that has the same attributes, but stored in a different memory address. If the object calling it stores other objects inside it, it can either recursively call those clone()
methods (creating a deep copy), or just leave them as references (shallow copy)
public class Square {
//Previous code...
public Square copy()
{
return new Square(this.length);
}
}
It can also be defined as a copy constructor