β Abstract classes / Interfaces, why do we use them?
What are the benefits of abstract classes or interfaces?
6 Replies
Why couldn't we just make a normal class for animal, and make a subclass for pig with the method inside it?
Should i use abstract classes / interfaces when i'm defining a method that has no attributes?
In your example, there's no benefit whatsoever
When you get onto more advanced code, it's not uncommon to have some amount of abstraction.
Let's say you have a logging library which can write log messages to a file, or a database, or a tcp socket. You don't want to pepper your code with
if (target == Target.File) /* Interact with a file */ else if (target == target.Database() /* interact with a database */
etc -- it's better to have your code interact with an ILogTarget
, which can be implemented by classes specific to interacting with a file, database, etc
Unfortunately, when you're teaching/learning a language, you're necessarily dealing with really simple examples, which often don't show the benefits of using abstractionHmm
I kind of understand what you mean
But not really tbh
I'll look it up in my freetime
thanks tho π«Ά
I think beginner doesn't need to understand what benefit can we get from using abstract and interface. But when u reading some open source code, for example: dotnet/eShop. U will see many OOP principles in it. So how do we use these principles to simplify our coding? That must use abstract and interface. Abstract classes simplify inheritance of attributes. Interfaces can simplify behavioral inheritance.
In this case I'd say that you will figure out why you need these once you need them
An interface defines "rules" on a class which it must implement. It can have multiple interfaces. Example could be a prop that has
IShootable
to indicate it can be short, or IBleedable
to indicate it can bleed. It's an abstraction which can then be checked instead of going through some hige list of props to find what it can do
Abstract is the same except it is a single class that can be inherited from. Big difference is that they already contain implementations, and often require more from the inheriting class to finish its behaviour.
Honestly, pointless to even explain this when the internet explains it better. There's SO MUCH involved it makes no sense to type it outI'd say class inheritance for things, interfaces for behaviors. For instance let's say you want a list of all types of animals, you can do that but let's say you want a list of things that can fly. You can use an interface to create a list of things that aren't all related besides the fact that they implement some functionality for fly. Like the list can contain a bunch of birds and a bunch of planes.