Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
Clay Janson96 Points
Why do we override the method? what is the need of overriding the methods??
Scott Brown6,969 Points
The purpose of overriding a method in a subclass is when you need the method to behave differently in the subclass than it does in the parent class / other subclasses.
For example, let's assume you are writing a Triangle class and a Square class, both of which extend the Shape class, and you want to have a method that calculates and returns the area. Since each type of shape has a different formula for calculating area, you'd want to override the area method in each subclass. Each subclass would have it's own code for calculating/returning the area, while still being able to reuse code that applies to all subclasses of Shape.
A good example of a method that wouldn't need overriding would be something like getNumberOfSides, since numberOfSides could be defined as a field in the Shape class, and set to the appropriate number in your Triangle and Square constructors.
Antonio Benincasa5,956 Points
The practice of overriding method is strictly related to the Inheritance paradigm. The inheritance is the practice to specialize the superclass. So, the subclass (inherited class) might need to change the behavior of a superclass method; this practice is called overriding.
You can find here some real world examples