Intro to Inheritance

CSCI 1933 – Introduction to Algorithms and Data Structures
Adriana Picoral

Object class

All classes in Java inherit from Object implicitly Add this to the main method in our Calculator class:

calc.toString();
calc.equals(anotherCalc)

Common Object Methods

We override these:

  • toString()
    • Guaranteed to exist
    • Not Guaranteed to be good
    • Called automatically in many places
  • equals(Object other)
    • Supposed to check “true” equality
    • Guaranteed to exist
    • Not Guaranteed to be good

Override toString() and equals(Object other)

Task: add toString() and equals(Object other) methods to our Calculator class

Test your code:

Calculator calc = new Calculator(10, 5.6);
Calculator anotherCalc = new Calculator(10, 5.6);
System.out.println(calc);
System.out.println(calc.equals(anotherCalc));
This Calculator has the following numbers: 10.0, 5.6
true

Gradescope submission

Submit your Calculator.java class with the following:

  • a static method isOdd(int number) that returns true (boolean) if the argument number is odd, false otherwise (solution on previous slides)
  • override the toString() method to return a string in the followin format "This Calculator has the following numbers: <left>, <right>"
  • override the equals(Object other) method to return true when this and other are the same object, or when this and other have the same left and right double numbers.

Solution

@Override
public String toString() {
  return "This Calculator has the following numbers: " + left + ", " + right;
}

@Override
public boolean equals(Object obj) {
  if (this == obj) return true;
  
  if (!(obj instanceof Calculator)) return false;
  
  // cast it to Calculator to access methods
  Calculator aCalculator = (Calculator) obj;
  
  // left and right are primitive types, so == should be used
  if (this.left != aCalculator.getLeft()) return false;
  if (this.right != aCalculator.getRight()) return false;
  
  return true;
}

Looking Back

  • All classes in Java inherit from Object implicitly, we often override toString() and equals(Object other) in the classes we write