Thursday, 29 August 2019

Method Overloading

Method over loading: A class contain more than one method with the same name
Constructor Overloading: A class contains more than one constructor

1.Number of parameters
2.Data types of parameters
3.Order of parameters

We cannot create a method inside a method.
We can overload main method also


Example:

public static void main(String[] args) {
   
        MethodOverloading obj=new MethodOverloading();
        obj.sum();
        obj.sum(10);
        obj.sum("Test");
        obj.sum(5, 10);
        }
     //We cannot create a method inside a method
     //duplicate method-same method name with same number of arguments(same data types) are not allowed
    //Method overloading-A class contain more than one method with the same name

   
   
    public void sum() {  //0 input parameter
        System.out.println("This is a method with zero parameters");
    }
   
    public void sum(int i) { // 1 input parameter(integer)
        System.out.println(i);
        System.out.println("This is a method with one input parameters");
    }

    public void sum(String s) {// 1 input parameter(String)
        System.out.println(s);
        System.out.println("This ia a method with one input parameter and string data type");
       
    }
   
    public void sum(int i,int j) { //2 input parameter
        System.out.println(i+j);
        System.out.println("this is a method with two input parameter");
    }
   
   
    public static void main(int p) {  //we can overload main method also
       
    }
   
    public static void main(String p) {
       
    }
}

Local And Global Variables

Example:
public class LocalVsGlobalVariable {

    //Global variable--class variables
    String name="John";
    int age=30;
   
    public static void main(String[] args) {
        int i=10;//local variable for main method
        System.out.println(i);//10
       
        LocalVsGlobalVariable obj=new LocalVsGlobalVariable();
        System.out.println(obj.name);
        System.out.println(obj.age);
    }

   
    public void sum() {
        int i=15; //local variable for sum method
        int j=20;   
    }
}


Constructor

1.Constructor is a special kind of method
2.Constructor name should be same as class name
3.Constructor will not return any value
4.Constructor will be invoked at the time object creation.
5.Constructor will take the parameters (just like a method)
6.Constructor is used for initialize the values.

Two types of constructors:

1.Default constructor
2.Parameterized constructor


This keyword
this keyword can be used for identify the variable in the class (while using same variables in the constructor)

No comments:

Post a Comment