ABSTRACT CLASSES AND
INTERFACES
ABSTRACT CLASS
● An abstract class is a class that is specifically defined to lay a foundation for
other classes that exhibits a common behaviour or similar characteristics.
● Used only as a base class for inheritance.
● It makes no sense to instantiate an abstract class because all the method
definitions are empty and must be implemented in a subclass.
EXAMPLE
Q) Write a program that has an abstract class Polygon. Derive two classes
Rectangle and Triangle from polygon and write methods to get the details of their
dimensions and hence calculate the area.
POLYMORPHISM
Polymorphism
Polymorphism is exhibiting differing behavior in differing conditions.
Polymorphism comes in two flavors.
1. Method Overloading
2. Method Overriding
Polymorphism
Python does not support method overloading like other languages. It will just replace the
last defined function as the latest definition.
We can however try to achieve a result similar to overloading using *args or using an
optional arguments.
class OptionalArgDemo:
def addNums(self, i, j, k=0):
return i + j + k
o = OptionalArgDemo()
print(o.addNums(2,3))
print(o.addNums(2,3,7))
Polymorphism
● Runtime polymorphism is nothing but method overriding.
● Method overriding is concept where even though the method name and
parameters passed is similar, the behavior is different based on the type of
object.
Polymorphism
class Animal: class Dog(Animal):
def makeNoise(self): def makeNoise(self):
raise NotImplementedError print("Woooooof")
class Cat(Animal): a = Cat();
def makeNoise(self): a.makeNoise() #Prints Meeeowwwwww
print("Meoooowwwww")
a = Dog();
a.makeNoise() #Prints Woooooof
Polymorphism
● In the above example we created class Cat and Dog which inherits from
Animal.
● We then implemented makeNoise method in both Cat and Dog class.
● At runtime it decides the type of object and calls the corresponding method
OPERATOR OVERLOADING
● The meaning of operators like +,-*,/,>,< etc are predefined in any programming
language.
● So programmers can use them directly on built in data types to write their
programs.
● Operator overloading allows programmers to extend the meaning of existing
operators so that in addition to the basic data types, they can also be applied to
user defined data types.
OPERATOR OVERLOADING
● With operator overloading, a programmer is allowed to provide his own
definition for an operator to a class by overloading the built in operator.
● Operator overloading is also known as operator adhoc polymorphism since
different operators have different implementations depending on their
arguments.