Method Overriding in java

Method overriding in java
  • Reuse ofmethod from super class in subclass by changing its implementation and keeping signature same is known as method overriding.
  • The subclass can change the implementation of super class method by overriding concept.
  • While overriding a method in subclass, it should retain same signature of super class and can change the implementation defined in the method body.
  • We can override following method of super class:
  1. static method
  2. Private method
  3. Final method
Use of Method Overriding
  • Method overriding is used for run time polymorphism.
  • With help of Method Overriding, we can provide specific implementation of a method that is already defined.
Lets understand the concept by below example:

[pastacode lang=”java” manual=”class%20Demo%0A%7B%0A%09void%20test()%0A%09%7B%0A%09%09System.out.println(%22running%20test%20method%22)%3B%09%0A%09%7D%09%0A%7D%0Aclass%20Sample%20extends%20Demo%0A%7B%0A%0A%20%20%20%20%20%20%20%20%20void%20test()%0A%09%7B%09%0A%09%09System.out.println(%22running%20overridden%20test%20method%22)%3B%0A%09%7D%0A%09%09%0A%7D%0Apublic%20class%20MethodOveriding%0A%7B%0A%09public%20static%20void%20main(String%5B%5D%20args)%0A%09%7B%0A%20%20%20%20%20%20%20%20System.out.println(%22**********************%22)%3B%0A%09%09%0A%20%20%20%20%20%20%20%20Sample%20obj1%3Dnew%20Sample()%3B%0A%09%09%0A%09%09obj1.test()%3B%2F%2F%20calling%20to%20non%20static%20test%20method%0A%09%09%0A%20%20%20%20%20%09System.out.println(%22**********************%22)%3B%0A%09%7D%0A%7D” message=”” highlight=”Example of Method Overriding” provider=”manual”/]

output:
**********************
running overridden test method
**********************

Run time Polymorphism in java

Leave a Reply