Saturday, 25 February 2017

What is Method Overriding In Java ?

Method Overriding :

It is also known as Run time polymorphism or dynamic binding. In Method Overriding we have more than one methods with same name and with same arguments , but in different class(means here one class extends other class).
In Method Overriding by default super class constructor is available in sub class.

There are some rules to achieved method overriding in Java :
  1. Methods must have same name.
  2. Methods must have same number of argument list.
  3. Method must have same return type.
  4. Only public, protected and default(same package) methods can be overridden.
  5. If method has default access, then overriding method must be default, protected or public.
  6. If method has protected access, then overriding method must be protected or public.
  7. If method has public access, then overriding method must be public.  
  8. Final methods cannot be overridden. Because final is used to declare constant.
  9. Static methods cannot be overridden. Because static method is available to all instance of super class and sub class.So it's not permissible to re-implement the static method in sub class.
  10. Use super keyword to invoke the parent class method from sub class.
  11. Constructor can not overridden.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class ParentClass {
 public ParentClass() {
  System.out.println("Default Parent Class Constructor");
 }
 void show(){
  System.out.println("Parent class Method");
 }
}
public class OverridingExample extends ParentClass {
 void show(){
  System.out.println("Sub class Method");
 }
 public static void main(String[] args) {
  OverridingExample o = new OverridingExample();
  o.show(); //Here Sub Class Method will execute
  
  ParentClass p = new OverridingExample();
  p.show(); //Here also Sub Class Method will execute, because parent class method will override in sub class
 }
}

Output :

Default Parent Class Constructor
Sub class Method
Default Parent Class Constructor
Sub class Method


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment