Methods

A simple introduction to the Methods


Declaring a Method


A Small Example for declaring a method.

void count( ){

}

I explain the above method.

void   - The keyword "void" is the return type of the method.

count - Name of the method.

( )      - Inside these brackets we can have the method parameters.

A simple programme for explain methods

Example 1 -
  
class Test{
    int x= 8;
    int y=3;

    void Add(){
        System.out.println("Addition :"+(x+y));
    }

    void Sub(){
        System.out.println("Subtraction :"+(x-y));
    }

    void Multiply(){
        System.out.println("Multiplication :"+(x*y));
    }

    void Divide(){
        System.out.println("Division :"+(x/y));
    }

    public static void main(String args[ ]){
        Test t= new Test(); /*Line A*/
        t.Add();                  /*Line B*/
        t.Sub();
        t.Multiply();
        t.Divide();
    }

}

Out put of the programme -
                                    Addition :11
                                    Subtraction :5
                                    Division :2
                                    Multiplication :24

Line A

Java is object oriented programming language.
To use one of the methods in Test class we must create a Test object out of the Test class.

From Line A-
        Creates a Test object (instance object) to use one of the above methods.
The created Test object will have all the behaviors (methods) and all the properties(variables) defined inside Test class.

The Test object will be created in an area called heap in the memory.

Line B

Call the method inside the Test object.

Method Overloading

Method Overloading means declaring several methods with the same name but with different parameter list in the same class.

A simple programme for Method Overloading

Example 2-

class Test1{
    void sum(int x,int y){                            
        System.out.println("sum :"+(x+y));
    }
    
    void sum(double x,double y){              
        System.out.println("sum :"+(x+y));
    }
    public static void main(String args[]){
        Test1 t1=new Test1();
        t1.sum(2, 3);
        t1.sum(2.53,3.53);
    }
    
}

Out put of the programme -
                                      sum :5
                                      sum :6.06

I think you get a some knowledge about Methods.
I will write some about method overloading in the object oriented concepts.

Hope you are enjoy my post.
see you soon.
Thank you.




Comments

Popular posts from this blog

Algorithm I

love java programming

Loops