Posts

Showing posts with the label Method overloading

Java Method Overloading Explained with Code Samples

Java method overloading allows defining two or more methods within the same class that share the same name. Method overloading makes the code clean and increases the readability of the code. Method overloading helps to achieve polymorphism which is one of the object oriented principles.  In this article, I will be covering method overloading in detail. Introduction When methods are overloaded, their parameter declarations need to be different. The following code demonstrates this: public class AdditionService {             int add() { // no parameters             return 3+5;       }             int add(int i) { //one integer parameter             return i+i;       }             int add(int i,int j) { //two integer parameters             return i+j;       }             double add(double i,double j) { //two double parameters             return i+j;       }            } This class has 4 methods with the name add . All four add methods differ in the parameters , so there is no compilation...

Method Overloading Vs Method overridding

  In this blog post, I will be explaining the difference between method overloading and method overidding. What is method overloading? In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. The following code demonstrates this: public class AddDemo {public int add(int a,int b){return a+b;}public double add(double a,double b){return a+b;}} So here this class has two methods with the name “ add “. The first version accepts two integer values and returns an int, whereas the second version accepts two double values and returns a double. So both these methods have the same name i.e. add , but accept different types of parameters. Overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types...