Algorithms and OOD (CSC 207 2014F) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [Learning Outcomes] [FAQ] [Teaching & Learning] [Grading] [Rubric] - [Calendar]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines] [Readings]
Reference: [Student-Curated Resources] [Java 8 API] [Java 8 Tutorials] [Code Conventions]
Related Courses: [CSC 152 2006S (Rebelsky)] [CSC 207 2014S (Rebelsky)] [CSC 207 2014F (Walker)] [CSC 207 2011S (Weinman)]
Misc: [Submit Questions] - [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] - [Issue Tracker (Course)] [Issue Tracker (Textbook)]
Overview
How does the weirdo equals
method work.
class Fraction
{
BigInteger num;
BigInteger denom;
...
public boolean equals(Object other)
{
// If the objects occupy the same area of memeory, they are
// the same
if (this == other)
{
return true;
} // this == other
// If the other object is a Fraction
else if (other instanceof Fraction)
{
return this.equals((Fraction) other);
// Fraction frac = (Fraction) other;
// return this.num.equals(frac.num) &&
// this.denom.equals(frac.denom);
} // other is a Fraction
// If the other object is a BigInteger
else if (other instanceof BigInteger)
{
return this.equals((BigInteger) other);
} // other is BigInteger
// Everything else is different.
else
return false;
} // equals(Object)
/**
* Determine if this fraction is the same as a BigInteger.
* A fraction is the same as a BigInteger when the denominator
* of the fraction is 1 and the numerator is the same as the
* BigInteger.
*/
public boolean equals(BigInteger other)
{
return this.denom.equals(BigInteger.ONE) &&
this.num.equals(other);
} // equals(BigInteger)
/**
* Determine if this fraction is the same as another fraction.
* Two fractions are the same if they have the same numerator
* and denominator.
*/
public boolean equals(Fraction other)
{
return this.num.equals(other.num) &&
this.denom.equals(other.denom);
} // equals(Fraction)
} // class Fraction
checkEquals(new Fraction(1,2), Calculator.eval1("1/2"));
// How JUnit deals with this.
// Evaluate the first value, call it v1
// Evaluate the second value, call it v2
// Call v1.equals(v2)
// If true, does nothing
// If false, reports an error
// JUnit assumes v1 and v2 are objects
// So Java looks for a method with signature equals(Object)
// to do the comparison.
checkEquals(new Fraction(1,2).toString(), Calculator.eval1("1/2").toString());
When we put the simplify
method (using gcd
) in the constructor, does
it need to be anywhere else?
Can we call constructors from other constructors?
Yes
public Fraction(BigInteger num, BigInteger denom) { this.num = num; this.denom = denom; } // Fraction(BigInteger, BigInteger)
public Fraction(int num, int denom) { this(new BigInteger(num), new BigInteger(denom)); } // Fraction(int, int)