Method Overloading (OOP - JAVA)

 Method Overloading

When we create same method continuously in a same class, we use method overloading concept.

We can change the parameters, when we performing method overloading. We can say it method signature as well.

Consider following code segment,

    eg:   class World{

               void countries(int x){

                  }

              void countries(String y){

                  }

             }   

Method signature segment has been painted in gray color. 

Consider following code segment,

void duneth(){

}

void duneth(String s){

}

void duneth(int x){

}

void duneth(int y, int z){

}


duneth(3, 87);

duneth();

duneth("Hello World");

duneth(123);


If you look at above coding segment carefully, you can see how to can we give our arguments according to the parameters.

Lets see another valuable codes and you can run them as your prefer. It will be easy to understand method overloading concept. 

public class Sum {
void sum(int a, long b){
System.out.println( a+b );
}
void sum(int c, int d){
System.out.println( c+d );
}

public static void main(String[] args) {
Sum s = new Sum();
s.sum(5, 123456789L);
s.sum(9,456);
}
}

Above example is relevant to method overloading concept. We have the same method in Sum class. It is sum. So, we have to make method signature by changing the parameters. In this case, there are different parameters for both methods. First method has int and long variables, Second method has only int variables. 

Inside the main method we have created a object called s

We need that object for accessing those methods through the object. As I have discussed earlier, we have to give arguments according to parameters. 

If you have understand the example well which I have explained previously, you can think about the following code given below.

public class StrIn {
void display(double a){
System.out.println("Double");
}
void display(String b){
System.out.println("String");
}

public static void main(String[] args) {
StrIn si = new StrIn();
si.display("gawesh");
si.display(78.98);
}
}


Access Modifiers

Consider the following code segment. 

default String a;

default class A{

}

default void a(){

}

In  this case a specific keyword has been applied before the variable, the class and  the method. 

What is that 🤔

The Security that has been given to access the classes, methods and variables are Access Modifiers. 

There are 4 access modifiers that we can use. 

  1. public - Can access entire project. Anything can access. 
  2. protected - Can access inside the class, package and subclasses(join classes).
  3. default - Can access inside the class and package.
  4. private - Can only access inside the class.

We can understand about access modifiers clearly by inspecting the below picture as well.


















Comments

Popular posts from this blog

Object Creation, Data Types (OOP - JAVA)

Upcasting and Downcasting (OOP - JAVA)