From the Previous Blog we have discussed some of the components of java. Here are some of the other features of java.
Method Overloading
When a single class has multiple methods with same name , this is concept is called as Method Overloading . The compiler differenciate b/w the 2 methods based upon the number and type of arguments.
Program:
// To illustrate method overloading
class SumDemo
{
void sum ( int a , int b)
{
System.out.println(" Sum of 2 number =" + (a+b));
}
void sum ( float a , float b)
{
System.out.println(" Sum of 2 floating point number =" +(a +b));
}
void sum ( int a ,int b , int c )
{
System.out.println(" Sum of 3 numbers =" + ( a+b+c));
}
}
class MethodOverloadDemo
{
public static void main ( String [] args )
{
SumDemo s = new SumDemo( );
s.sum(12 ,13,15);
s.sum( 2.5F , 6.789F);
s.sum( 33, 678 );
}
}
Constructor Overloading
Like method overloading , constructor can be overloaded in the same manner. The compiler differenciates based on the number and type of arguments.
Program:
// To illustrate constructor overload
class Sum
{
Sum ( int a , int b)
{
System.out.println (" Sum of 2 number is =" + (a+b));
}
Sum ( float a , float b )
{
System.out.println ( " Sum of 2 float number is =" + (a+b));
}
Sum ( int a , int b , int c )
{
System.out.println (" Sum of 3 numbers is =" + (a+b+c));
}
}
class ConstOverloadDemo
{
public static void main ( String [] args )
{
Sum s = new Sum( 12 ,12,223);
Sum s = new Sum (23.4F , 34.8F);
Sum s = new Sum ( 25 , 34 );
}
}
Recursion
Recursion is a process in which a method calls itself again and again.
Program:
// Program to find factorial of a number
class Factorial
{
int fact ( int n )
{
int r ;
if ( n==1 )
return 1;
r = fact ( n-1) * n;
return r ;
}
} Output:
class recursion Factorial of 4 = 24
{
public static void main ( String [] args )
{
Factorial f = new Factorial ();
System.out.println (" Factorial of 4 =" + f.fact(4));
}
}
No comments:
Post a Comment