Understanding Method Overloading and Overriding in Java: A Practical Guide
In this recitation, we will explore the concepts of method overriding and overloading in Java, focusing on the `equals()` method. We will implement method overloading for the `equals()` in the `LineSegment` class and overriding it in the `LineSegmentCollection` class, which extends `Object`. Key tasks include ensuring that the `equals()` method correctly compares objects based on properties like size and attributes. We also provide detailed setup instructions for your project, encouraging questions on submission procedures to clarify any uncertainties.
Understanding Method Overloading and Overriding in Java: A Practical Guide
E N D
Presentation Transcript
Recitation 8 October 15, 2010
Today’s Goals: • Overriding versus overloading a method • Implement overloading the equals() on LineSegment class • Implement overriding the equals() on LineSegmentCollection class
Extending the Object class • All classes extend the Object class either directly or indirectly
Overloading Object equals() public booleanequals(Example otherExample) { if (otherExample != null) { return (this.getX() == otherExample.getX() && this.getY() == otherExample.getY()); } else return false; } equals defined in Example & Object
Overriding Object equals() public boolean equals(Object obj) { if(objinstanceof Example && obj != null) { Example otherObj = (Example)obj; return (this.getX() == otherObj.getX() && this.getY() == otherObj.getY()); } else return false; } equals defined in Example
Recitation Specification • Copy classes and interfaces created last week • OverloadLineSegment equals() method: • Return true if the properties of the LineSegment equals that of the object passed in. • Should have a type of LineSegment, not ALineSegment or AVerticalLineSegment • OverrideALineSegmentCollection equals() method: • Check the size of both collections and match each object for all possible indexes. • Add objects of type ALineSegment and AVerticalLineSegment to the collection. • Call equals on LineSegments and LineSegmentCollections that are the same and different. Output the result to the console.
Setup and Submission • Please follow the instructions on the course website to set up and submit your projects! • Set up your project: • http://www.cs.unc.edu/~dewan/comp114/f10/Recitations/makeproject/ • Submit an assignment: • http://www.cs.unc.edu/~dewan/comp114/f10/Recitations/submit/ • Ask us if you have *ANY* questions on submission
Setting up Object Editor • Recall from lecture: • Jar must be on build path • Import statement necessary! • import bus.uigen.ObjectEditor; • Must call ObjectEditor.edit(yourObject);