In: Computer Science
WRITE IN JAVA
1) Create a constructor that can create objects in the following way: c = Circle(X, Y, R);
2) Please add a constructor that only accepts R value and initializes the Circle at the origin.
3) Please implement a constructor that behaves the same way as the default constructor.
4) Add a method named “touches” to the Circle class which receives another Circle instance and checks whether these two circles touch each other externally and only at one point. The method should return a Boolean value and will be called like this: c1.touches(c2) //returns either true or false.
5) Please implement a Test class with main method that simulates
each of the following
cases and prints their outcome to the screen.
Circle.java :
public class Circle {
private int x,y,radius;
// Constructor with no parameter (this Constructor will behave as default Constructor)
public Circle() {
}
// Constructor with one parameter
public Circle(int R) {
/*
R: radius of circle (integer value)
initialize radius with provided radius and center as origin (x=0 and y=0)
*/
radius = R;
x = 0;
y = 0;
}
// Constructor with three parameter
public Circle(int X,int Y,int R) {
radius = R;
x = X;
y = Y;
}
// method to check if two circle touches externally at one point or not.
public boolean touches(Circle c) {
/*
two circle touches each other if distance between center of circles is equals to sum of radius of circles
formula for distance between two point = sqrt((x1-x2)^2 + (y1-y2)^2)
sqrt denotes square root.
*/
double centerDistance = Math.sqrt(Math.pow((getX() - c.getX()),2) + Math.pow((getY() - c.getY()),2));
int radiusSum = getRadius() + c.getRadius(); // sum of radius
/*
check if centerDistance and radiusSum is equal or not if yes then return true
otherwise return false.
*/
if(centerDistance == radiusSum) {
return true;
}
return false;
}
/*
getter methods for instance variables x , y and radius
*/
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getRadius() {
return radius;
}
}
Main.java (Test class with main method):-
public class Main
{
public static void main(String[] args) {
// creating two Circle object c1 and c2
Circle c1 = new Circle(2,4,6);
Circle c2 = new Circle(1,2,4);
// Checking touches method of Circle class
System.out.println("touches Circle(2,4,6) and Circle(1,2,4): ? "+c1.touches(c2));
// creating two Circle object c3 and c4
Circle c3 = new Circle(12,9,10);
Circle c4 = new Circle(0,0,5);
// Checking touches method of Circle class
System.out.println("touches Circle(12,9,10) and Circle(0,0,5): ? "+c3.touches(c4));
}
}
Sample Output :
Please refer to the Screenshot of the code given below to understand indentation of the code.
Screenshot of Circle.java
Screenshot of Main.java :-