Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Showing posts with label Overriding in Java. Show all posts
Showing posts with label Overriding in Java. Show all posts

Sunday

Difference between method overloading and method overriding in Java

Difference between method overloading and method overriding in Java

This is one of the important tricky programming interview questions asked in Java. Here are the basic differences between method overloading and method overriding in Java.


  1. Method Overloading occurs while compile time and Method Overriding occurs while runtime.
  2. Method Overloading occurs in same class and sub class, but overriding occurs only in subclass.
  3. Static methods can be overloaded, but you can't override static methods.
  4. For overloading method signature has to be changed, but for overriding it's not needed.
  5. Private and final methods can be overloaded but cannot override.

Saturday

Method Overriding in Java

Method Overriding in Java:

                                             We studied about method overloading in Java.Now the next is Method Overriding in Java. Here the number of arguments and datatype and all are same.
  1. Used in parent class and child class.
  2. Parent class method is Overriding by Child class.
  3. number of arguments are same.
  4. datatype of arguments are also same.
  5. Method name is same.
  6. The example is when a method in a Interface have to behave differently in different scenarios.
Example:

package com.jobberindia;

public interface Test {
void performSomeTask(int a,int b);
}


           
package com.jobberindia;
import java.io.File;
import java.util.*;
public class HelloWorld implements Test{

@Override
public void performSomeTask(int a, int b) {
// TODO Auto-generated method stub
System.out.println("subtracting "+a+" from "+b+" is: "+(a-b));
}

public static void main(String[] args) {
Test t =  new HelloWorld();
t.performSomeTask(55, 15);
}
}