Method overriding is an easy concept of OOP if you already know what inheritance is.
What is the Method overriding?
Let’s understand the method overriding through an example –
In the following code, you can see there are two classes – ParentClass
that has a method called abc()
, and ChildClass
that has inherited the ParentClass
.
class ParentClass{
function abc(){
// Instructions
}
}
class ChildClass extends ParentClass{
}
Now, what If we create a method in the ChildClass
with the same name that already exists in the ParentClass
. In our case, the method name is abc()
.
class ParentClass{
function abc(){
// Instructions
}
}
class ChildClass extends ParentClass{
function abc(){
// Different Instructions
}
}
Yes, you can create a method with the same name that already exists in the Parent, and it is called method overriding. The child class method will override the parent class method.
When you create an object of the child class and call a method that is also present in the parent class, then it will run the method of the child class.
What is the Property overriding?
It is the same as the method overriding, but here you override a property.
Example of the Property overriding
When you access the name
property through a child class object, then it will be Mark
.
class ParentClass{
name = "John";
}
class ChildClass extends ParentClass{
name = "Mark";
}