Monday, August 29, 2011

Static method example in java

//StaticMemberClass.java
public class StaticMemberClass
{
static final double pi = 3.14;
static void areaOfCircle(double r)
{
System.out.println("Area of a circle of radius "+r+" = "+pi*r*r);
}
}

//MainClass.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainClass
{
public static void main(String args[]) throws IOException
{

double radius;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter redius: ");
radius = Double.valueOf(br.readLine()).doubleValue();

//No need to create an object to call a static members.
/*StaticMemberClass s = new StaticMemberClass();
s.areaOfCircle(radius);*/

StaticMemberClass.areaOfCircle(radius);
}
}





Output=>
Enter redius: 2
Area of a circle of radius 2 = 12.56

No comments:

Post a Comment