Method Overriding in Java

 

In parent class we have a method, and the same method is declared in child class is known as method overridding. Before we have seen method overloading, now we will discuss method overriding in detail.

Rules of Method overriding:

  1. method in child class must have the same name as method in parent class.
  2. method must have the same no. of parameters
  3. method must have the same data types of parameters
  4. method must have the same return type
  5. must be a IS-A relationship i.e. inheritance
  6. The Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class.
  7. private, static and final methods cannot be overridden.
  8. Binding of overridden methods happen at run time which is known as dynamic binding.

We will look into the implementation of all these rules with examples.

 First, understand the simple usage of method overriding with the below example.

We have 2 classes called Color and TestColor. Create an object of Color class and call the method to get the color.I want red color, but it will print green as mentioned in the method getColor.

Output : I will get green

I wanted the color Red, but it prints green because that is by default output of the method in parent class Color which is extended by the child class TestClass.

How to resolve this issue or say how to get red color?

You have to override the method and use specific implementation.

Output : I will get Red

Let’s understand with one more practical example.

Consider we have one general class Company which returns the notice period in months. Now, notice period may vary from company to company. Say IBM has 1 month notice period and Yahoo another class has 2 months notice perios. Now, how to set the specific implementation as per need of different companies.

Output :Notice period in IBM 2 months
Notice period in Yahoo 3 months

 

Can we override static methods?

No, we can not override static method. Reason is that static method is bound with class whereas instance method is bound with object.

Can we override main method?

No, because main method is static.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Print Friendly, PDF & Email
Method Overloading in java
super keyword in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. August 4, 2015

    […] In the previous session, we have seen the usage of method overriding. […]

Leave a Reply

Your email address will not be published. Required fields are marked *