100 likes | 217 Views
This exercise explores the Java programming concepts of objects, references, and comparison methods using a Species class. The Species class models biological species with attributes such as name, population, and growth rate. Key functionalities include methods for reading input, writing output, calculating projected populations based on growth rates, and comparing objects using both reference equality and the equals method. By engaging in practical coding examples, learners will gain a solid grasp of how to manage and compare objects in Java.
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)); }