Method overriding:
- Defining a method in the Child class with same name and same set of arguments of Parent class method.
- When two methods in Parent and Child with the same identity, it gives the first priority to Child object.
class Parent:
def fun(self):
print("Parent's fun()")
return
class Child(Parent):
def fun(self): #override
print("Child's fun()")
return
class Inheritance:
def main():
obj = Child()
obj.fun()
return
Inheritance.main()
When we access the functionality using Child object, it is looking for Child object first, if it is not available in Child, then it looks into Parent class.
class Parent:
def m1(self):
print("Parent's m1()")
return
def m2(self):
print("Parent's m2()")
return
class Child(Parent):
def m2(self): #override
print("Child's m2()")
return
class Inheritance:
def main():
obj = Child()
obj.m1()
obj.m2()
return
Inheritance.main()
Advantage of overriding:
- Overriding is the concept of updating existing object functionality when it is not sufficient to extended object.
- Re-writing the function logic with the same identity.
Complete Inheritance with Code program:
# 1. Accessing existing functionality
# 2. Adding new features
# 3. Update(override) existing features
class Guru:
def call(self):
print("Guru - Call")
return
def camera(self):
print("Guru - Camera - 2MP")
return
class Galaxy(Guru):
def videoCall(self):
print("Galaxy - Video Call")
return
def camera(self):
print("Galaxy - Camera - 8MP")
return
class Inheritance:
def main():
g1 = Galaxy()
g1.call()# Access existing
g1.videoCall()# new feature
g1.camera() #updated
g2 = Guru()
g2.call()
g2.camera()
g2.videoCall() # error:
return
Inheritance.main()