In: Computer Science
WRITE A JAVA PROGRAM - define a class that maintains information about circles in 2 dimensional plane. Be sure to include required data members and methods to initialize a circle object. provide information on the circle and reposition the circle. do not specify any other methods . in addition make sure data members are accessible in derived classes..
Code:
//class Circle
public class Circle{
//data members -- X and Y coordinates and the radius
public double x;
public double y;
public double radius;
//constructor which only takes one parameter radius and sets others as zero
Circle(double _radius){
this.x = 0;
this.y = 0;
this.radius = _radius;
}
//constructor with 3 parameters to define all the properties
Circle(double _x,double _y, double _radius){
this.x = _x;
this.y = _y;
this.radius = _radius;
}
//repositioning the circle requires to change the X and Y coordinates hence the parameters
void reposition(double _x,double _y){
this.x = _x;
this.y = _y;
}
//return the information about circle, its X, Y and Radius
String getInfo(){
return "X: "+x+" | Y: "+y+" | Radius: "+radius;
}
}
Refer to the screenshot for better understanding of the code:
A 2D circle would have the X and Y coordinates and its radius. Therefore we have these 3 data members in the Circle class. For initializing the object, we can have 2 constructors, one takes only the radius and sets X and Y to be 0, whereas other defines all the three properties.
The reposition method returns nothing. It only changes the value of X and Y as received in the parameters. getInfo() mehtod returns a string which has all the properties of the circle inside it.
To make the data members accessible in the derived classes, we have used the 'public' keyword before them. It makes them accessible in the sub-class of all the packages and classes.