Java Exercise: Create an object called Circle and write a test program that uses
ID: 3556107 • Letter: J
Question
Java Exercise:
Create an object called Circle and write a test program that uses the Circle class.
Details for your Circle object:
Two private instance variables: radius (of type double) and color (of type String), with default value of 1.0 and "red", respectively.
Two overloaded constructors (one that takes in no parameters and one that accepts a double (to be assigned to the radius)
Two public methods: getRadius() and getArea().
Diagram for reference:
Details for your test program:
Declare instances of the Circle class to be able to pint out the results.
When you done, send me both files, and a screen shot of your results after running your test program.
Explanation / Answer
Code:
public class Circle{
double radius=1;
String color="red";
public Circle(){ //default constructor
}
public Circle(double r){
radius=r;
}
public double getRadius(){
return radius;
}
public double getArea(){
return Math.PI*radius*radius;
}
//Testing function
public static void main(String []args){
Circle c1 = new Circle(); //initilised with default constructor
Circle c2 = new Circle(2); //initilised with constructor that takes radius as argument
System.out.println(c1.getRadius());
System.out.println(c2.getRadius());
System.out.println(c1.getArea());
System.out.println(c2.getArea());
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.