Override means having two methods with the same name but doing different tasks. It means that one of the methods overrides the other.
If there is any method in the superclass and a method with the same name in a subclass, then by executing the method, the method of the corresponding class will be executed.
Let's take an example on this.
- Python 2
- Python 3
class Rectangle(): def __init__(self,length,breadth): self.length = length self.breadth = breadth def getArea(self): print(self.length*self.breadth," is area of rectangle") class Square(Rectangle): def __init__(self,side): self.side = side Rectangle.__init__(self,side,side) def getArea(self): print(self.side*self.side," is area of square") s = Square(4) r = Rectangle(2,4) s.getArea() r.getArea()
Since the method from the coressponding class came into action, it means that one overrode the other.
Execution of 'getArea' on the object of Rectangle (r) printed "8 is area of rectangle" from the 'getArea' defined in the Rectangle class whereas, execution of 'getArea' on the object of Square (s) printed "16 is area of square" from the 'getArea' defined in the Square class.
It is very useful because it prevents us from making methods with different names and remembering them all.
There is not much to explain in this chapter. So, it is recommended to solve questions to get things clearer.