+ 1
Abstract Classes
Why there is need to use abstract classes in python if we can use normal?
6 Respuestas
+ 5
HonFu and I don't know a thing about Python, but Sahil Rana let me give you a picture of why do we need an abstract class at all.
Consider a class shape. Now classes like circle, triangle, squares, rectangles are all inheriting the shape class.
Now tell me is it necessary or any need for you to create an object or instance of the shape class?
The answer is "No" because now you have your own shapes and you can create objects of that type.
But consider that the shape class has some methods that are useful in your subclasses so now you can easily use them or if you want it to do something specific for your subclass then you can override them.
So the abstract class is there to kind of tell you that, kindly use my variables or methods to make objects of your own type. It kind of gives a structure for all your subclasses.
Edit: Abstract classes can have abstract methods which need not have an implementation or definition. They can also have non-abstract methods.
Also an abstract class cannot be instantiated.
+ 2
Avinesh, I couldn't be sure because I know very little about Java. 😅
+ 2
Off topic but I can't help it:
In Java, interfaces can nowadays provide default implementations and you can subtype them, too. Which seemed to me like the main purposes of abstract classes. What actual differences are there between interfaces and abstract classes still?
- Abstract classes can provide constructors
- Abstract classes and their subclasses have access to properties and can define new ones, interfaces don't
- Abstract classes can implement multiple interfaces, interfaces can't
How much is that worth? Not sure ¯\_(ツ)_/¯, in Java abstract classes are probably necessary occasionally, but I prefer to use interfaces wherever possible, and it's possible almost all of the time.
Rust takes the Haskell approach and it has only interfaces (kinda), and no classes. Works just fine.
+ 1
I think it's for cases when you want to prevent, that instances are built using the base class.
But I haven't used it myself yet, maybe someone can report their experience?
0
Ok! consider below ,it is not an abstract class but still i can override the unimplemented method in subclass. and i can always use base class menthod using super keyword() why do i need abstract class for this purpose now?
class parent:
def eyecolor(self):
pass
class child(parent):
def eyecolor(self):
print(“Blue”)
above i have done direct subclassing without the use of abstract base class
I read smwhr side effect of using direct subclassing is that “it becomes possible to find all the implementations by asking base class for the list of known classes derived from it”
can anyone plz explain hw its possible to fetch list of all derived classes and why this is wrong practice?