100 likes | 205 Views
Day double 11.0. 4.3 Objects and References. Exercise:. Species - name: String
E N D
Day double 11.0 4.3 Objects and References
Exercise: Species - name: String - population: int- growthRate: double+ readInput(): void+ writeOutput(): void+ projectedPopulation(int years): int+ set(String newName, intnewPopulation, double newGrowthRate): void+ getName(): String + getPopulation(): int+ getGrowthRate(): double+ equals(Species otherObject): boolean
Reference • The memory address of where an object is called a reference to the object
Reviewing comparing primitives int x = 5; int y = 6; if (x == y) { System.out.println(“They are equal.”);} else{ System.out.println(“They aren’t equal.”);}
Reviewing comparing primitives String x = “Bob”; String y = “Chucky”; if (x == y) { System.out.println(“They are equal.”);} else{ System.out.println(“They aren’t equal.”);}
Comparing objects *See handout
Comparing objects Can we use == to compare objects? Or should we use .equals to compare objects? Let’s experiment!
Comparing objects Create objects s1 and s2 for the class studentInfotry this:
if (s1 == s2)System.out.println(“Match with ==.” ); else System.out.println(“Doesn’t match with ==.”); // versus if (s1.equals(s2)) System.out.println(Match with the method equals.”); else System.out.println(“Doesn’t match with method equals.”);
Boolean comparison of objects public boolean equals(Species otherObject){ return ((name.equalsIgnoreCase(otherObject.name)) && (population == otherObject.population) && (growthRate == otherObject.growthRate)); }