DEV Community

Discussion on: Do you really understand interfaces?

Collapse
 
askeridos profile image
Adam AUTUORI • Edited

2/2

So, each class (Lion, Cat, ...) will be redefined the methods of the abstract class. This highlights the notion of polymorphism: the overload of method applied to inheritance.
All these animals have their own cry, eat their own food, ...

Pay attention to the syntax: if you want to create a Lion, it's an Animal:
Animal jungleKing = new Lion ("Simba");

The abstract class therefore makes it possible to implement members common to more specialized classes (going down in the hierarchy of the classes) and to define all or part of the methods.
You can create a consistent hierarchy even if you only know part of the system.

I hope I have explained well. You can translate the link from OpenClassrooms and read the full course.

Thread Thread
 
gaurang847 profile image
Gaurang

I read the full course using Google Translate. The translation wasn't perfect. But it worked I guess.
I found it to be a great read.
You explained well. But, I feel you missed the most important point of abstract classes.

We can see that our class Animalis declared abstract and that our daughter classes inherit from it. In addition, our daughter classes only redefine two methods out of four, so we conclude that these two methods must be abstract.

This line is important.
If all the methods in the abstract class are abstract, I see no point in such an abstract class. Since, it is essentially an interface then.

When you write a class that extends another normal class, you can either override the methods from the base class. Or you can leave them untouched.
You'd want to create an abstract class when you know that,

  • there are some methods in the base class that will definitely be overridden in the derived classes.

    eg. cry() - Dog, Cat and Lion each have a different cry

  • there will be some methods that won't be overridden in any of the derived classes.

    eg. walk() - Dog, Cat and Lion each walk the same way.

Whether the walk method is actually overridden in the derived class or not, doesn't matter.
But, an abstract class lets me provide the definition of walk method that I believe will be common in all the derived classes. Basically, it lets me provide a default for the walk method.
And, at the same time, it lets me enforce that the derived classes implement the cry method.

If you already understand this, then great!
But if you didn't, I hope I was clear enough.
Again, I'm more interested in a practical example where you've actually created an abstract class while writing software. So, whenever you do that, I'd be happy to hear about it :)

Thread Thread
 
askeridos profile image
Adam AUTUORI

Yeah, i forgot the principle to define default methods with abstract keyword. Your explanation seems better than mine. Thanks !