Credits

Saturday, July 3, 2010

Another Java Constructor Sample

When an object is defined, we can also access methods and fields. Below is another use of constructor and accessing instance variables for use.

[+/-] show/hide



import java.io.*;
public class CircleQuiz {
double radius;
double area, diameter;
CircleQuiz()
{ radius=1;}
public static void main(String args[]) throws IOException{

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
CircleQuiz x=new CircleQuiz();
String str;
double r;

System.out.println("use of Constructors:");
System.out.println("Default radius from a constructor: "+x.getRadius());

System.out.println("New Input for radius:");
System.out.println("Input radius :");
r=Double.parseDouble(br.readLine());



if (r<=0) r=x.radius; x.setRadius(r); System.out.println("Diameter "+x.computeDiameter(r)); System.out.println("Area"+x.computeArea(r)); } double getRadius() { return radius;} void setRadius(double x) { radius=x;} double computeDiameter(double r ) { double circleDiameter =r * 2; return circleDiameter;} double computeArea(double r ) { double circleArea =3.14 * r * r; return circleArea;} }

AddThis