OOPJ Practical No-7
OOPJ Practical No-7
Recursive methods
A method that calls itself is called recursive method.
Recursive methods must have a termination condition to avoid infinite recursion.
A recursive method normally made of an if-else statement. This if-else statement has termination condition
to decide whether the method must be called again or it should exit from loop of calling method again and
again.
Method Overloading
“Method which is having same name but differs- either in number of arguments or type of those arguments
called method overloading”.
Return type does not considered at the time of method overloading.
Method overloading is done only in same class.
In method overloading method is called depending on number of argument or type of argument passed.
In method overloading compiler resolves call at compile time hence it is also known as compile time
polymorphism.
Programs:
1. Program to count the number of objects made of a particular class using static variable and static
method and display the same.
public class ObjectCount
{
static int count=0;
ObjectCount()
{
count++;
}
static void display()
{
System.out.println("Number of object created: "+count);
}
public static void main(String[] args)
{
ObjectCount oc1=new ObjectCount();
ObjectCount oc2=new ObjectCount();
ObjectCount.display();
}
}
2. Program to find value of y using recursive function (static), where y=x^n
import java.util.*;
public class PowerCalculator
{
static double power(double x, int n)
{
if(n == 1)
return x;
else
return x * power(x, n-1);
}
public static void main(String args[])
{
double x, y;
int n;
Scanner s = new Scanner(System.in);
y = PowerCalculator.power(x, n);
System.out.println("y:= "+y);
}
}
3. Program to display area of square and rectangle using the concept of overloaded functions.
public class Shape
{
double calculate(double side) // Overloaded method for calculating area of square
{
return (side * side);
}
double calculate(double height, double width) // Overloaded method for calculating area of rectangle
{
return (height* width);
}
public static void main(String[] args)
{
Shape s = new Shape();
double area;
area = s.calculate(4.5);
System.out.println("Area of Square: "+area);