Wednesday 20 November 2013

Session 9:- Overloading In Java

        Overloading

  •  In a class, we have more than one method, with the same name but change in the parameter or signature is called as method overloading.
  • Change in the signature means there has to be change, 
  • In the number of parameter. 
  • Change in the data type of the parameter. 
  • There has to change in the sequence of the parameter. 
  • In case of overloading return type is not considered and the Access Specifier also not consider.  
  • Same rule is applicable even for constructor overloading.
Example 13:- Method Overloading

public class Calculator
{
public void addition(int a, int b)
{
int sum=a+b;
System.out.println ("Ans is:-"+sum);
}
public void addition(int a, int b, double c)
{
double sum=a+b+c;
System.out.println ("Ans :"+sum);
}
public void addition(int a, double c, int b)
{
double sum=a+b+c;
System.out.println("Ans :"+sum);
}
public double addition(double c ,int b, int a)
{
double sum=a+b+c;
return sum;
}
}
public class Test{

public static void main(String args[])
{
Calculator c= new Calculator();
 c. addition(12,20);
c. addition(4,10,7.9);
//Overloaded Methods
c. addition(1,3.5,34);
double sum= c. addition(0.3,25,30);
System.out.println ("Ans:"+sum);
}
}

Advantage:-
  • We can create only one object at time and call any number of methods by using the object reference variable.
Example 14:- Constructor Overloading

public class Student {
String name;
int age;
String email;
public Student()
{
System.out.println("default constructor");
}
public Student(String name)
{
this.name=name;
// local variable and instance variable name same
System.out.println ("one parameter constructor”);
System.out.println ("Name:-"+this.name);
}

public Student(String name, int age)
{
this.name=name;
this.age=age;
System.out.println ("two parameter constructor”);
System.out.println ("Name:-"+this.name);
System.out.println ("Age:-"+this.age);
}
public Student(String name, String email, int age)
{
this.name=name;
this.age=age;
this.email=email;
System.out.println("Three parameter constructor");
System.out.println ("Name:-"+this.name);
System.out.println ("Age:-"+this.age);
System.out.println ("Email:-"+this.email);
}
}
public class Test{
public static void main(String args[]) {
Student s= new Student();
Student s1= new Student("JNext");
Student s2= new Student("JNext",23);
Student s3= new Student("JNext","info@JNext.co.in",23);
}
}
OUTPUT:
default constructor
one parameter constructor
Name:-JNext
two parameter constructor
Name:-JNext
Age:-23
Three parameter constructor
Name:-JNext
Age:-23
Email:-info@JNext.co.in





1 comment:

  1. if you have any question than you can ask your question i will give ans to you..

    ReplyDelete