Friday, 29 September 2017

Object Oriented Programming : Methods

1.Methods in Java

Method describe behavior of an object. A method is a collection of statements that are group together to perform an operation.

Syntax:

modifier return-type methodName ( parameter-list )
{
       //body of method
}

Example of a Method

public String getName(String st)
{
String name="betheDeveloper.com";
name=name+st;
return name;
}

Modifier : Modifier are access type of method and its optional to use.

Return Type : A method may return value.

Method name : Actual name of the method.

Parameter : Value passed to a method.

Method body : Collection of statement that defines what method does.

Parameter Vs. Argument:

Parameter is variable defined by a method that receives value when the method is called. Parameter are always local to the method they dont have scope outside the method. While argument is a value that is passed to a method when it is called.

The finalize( ) Method:

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general form:

protected void finalize( )
{
   // finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.

2.Call-by-value and Call-by-reference

There are two ways to pass an argument to a method.

Call-by-value:

In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments.

Call-by-reference:

In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.

NOTE : In Java, when you pass a primitive type to a method it is passed by value whereas when you pass an object of any type to a method it is passed as reference.

Example of call-by-value.

public class Test
{
    public void callByValue(int x)
    {
        x=100;
    }
    public static void main(String[] args)
    {
       int x=50;
        Test t = new Test();
        t.callByValue(x);//function call
        System.out.println(x);
    }
   
}
Output : 50
Example of call-by-reference.

public class Test
{
    int x=10;
    inty=20;
    public void callByReference(Test t)
    {
        t.x=100;
        t.y=50;
    }
    public static void main(String[] args)
    {
      
        Test ts = new Test();
        System.out.println("Before "+ts.x+" "+ts.y);
        ts.callByReference(ts);
        System.out.println("After "+ts.x+" "+ts.y);
    }
   
}
Output :
Before 10 20
After 100 50

3.Method Overloading in Java

If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

Advantage of method overloading:

Method overloading increases the readability of the program.

Different ways to overload the method:

By changing number of arguments.

By changing the data type.

NOTE : In java, Methood Overloading is not possible by changing the return type of the method.

In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.

Different ways of Method overloading

1 Method overloading by changing data type of Arguments:

Example

class Calculate
{
void sum (int a, int b)
{
  System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
  System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
  Calculate  cal = new Calculate();
  cal.sum (8,5);      //sum(int a, int b) is method is called.
  cal.sum (4.6, 3.8); //sum(float a, float b) is called.
}
}
Output :

Sum is 13
Sum is 8.4
You can see that sum() method is overloaded two times. The first takes two integer arguments, the second takes two float arguments.

2. Method overloading by changing no. of argument:

Example

class Area
{
void find(int l, int b)
{
  System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h)
{
  System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args)
{
  Area  ar = new Area();
  ar.find(8,5);     //find(int l, int b) is method is called.
  ar.find(4,6,2);    //find(int l, int b,int h) is called.
}
}
Output :
Area is 40
Area is 48

In this example the find() method is overloaded twice. The first takes two arguments to calculate area, and the second takes three arguments to calculate area.

Example of Method overloading with type promotion.

class Area
{
void find(long l,long b)
{
  System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h)
{
  System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args)
{
  Area  ar = new Area();
  ar.find(8,5);     //automatic type conversion from find(int,int) to find(long,long).
  ar.find(2,4,6)    //find(int l, int b,int h) is called.
}
}
Output :
Area is 40
Area is 48

Q. Why Method Overloaing is not possible by changing the return type of method???

In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur. because there was problem.

class Calculation3{ 
  int sum(int a,int b){System.out.println(a+b);} 
  double sum(int a,int b){System.out.println(a+b);} 
 
  public static void main(String args[]){ 
  Calculation3 obj=new Calculation3(); 
  int result=obj.sum(20,20); //Compile Time Error 
 
  } 
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called.

Variable Arguments(var-args):

typeName... parameterName

In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.

Example

public class VarargsDemo {

   public static void main(String args[]) {
      // Call method with variable args 
  printMax(34, 3, 3, 2, 56.5);
      printMax(new double[]{1, 2, 3});
   }

   public static void printMax(double... numbers) {
   if (numbers.length == 0) {
      System.out.println("No argument passed");
      return;
   }

   double result = numbers[0];

   for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println("The max value is " + result);
   }
}
Output:

The max value is 56.5
The max value is56.5

No comments:

Post a Comment

Abstract Class & Interface in Java

      Abstract Class & Interface in Java         Here is the most important topic on Java Abstract class and interface, Abstraction ...