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! While you're at it, check out some resources Treehouse students have shared here.
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 trialKyle McCullen
16,639 PointsInterface Advantage
What is the advantage of using an Interface just to override all the methods in the interface in a separate class that implements the Interface? Why not just create the needed methods in a normal java class?
1 Answer
Linda de Haan
12,413 PointsLet me answer this with an example.
So an interface contains one or more methods without a method body (most of the times) that classes that implement the interface have to override.
Let's say you have a class Dog, a class Snake and a class Scorpion. Dog, Snake and Scorpion are all children of the parent class Animal and so inherit all methods from class Animal. But Snake and Scorpion both share behaviours that Dog doesn't have, for example a snake and scorpion are both venomous and a dog isn't.
That's why we use interfaces: to group certain behaviours which can be implemented by multiple classes (even if they don't share a parent). So classes Snake and Scorpion could implement an interface called Venomous with an abstract method called attackWithVenom(). Now a snake attacks in a different way than a scorpion. A snake bites and a scorption stings. So the attackWithVenom() method of Snake looks different than the attackWithVenom() method of Scorpion.
So when a class implements a certain interface, it promises to provide implementation to all the abstract methods declared in that interface. It also makes code easier readable, because once you see 'public class Snake implements Venomous' you know that this class will have Venomous behaviours implemented.
I hope that answers your question :)
Kyle McCullen
16,639 PointsKyle McCullen
16,639 PointsThanks!