We have an external (not within the main class) subclass Circle() in our project
ID: 3733660 • Letter: W
Question
We have an external (not within the main class) subclass Circle() in our project. It is instantiated as an object, myCircle(). In myCircle, we have a get and set method to determine the area as such:
Where it is bold, I added that part of code but I am still missing how the main class accesses the methods. Not sure what I'm missing.
Main class would look like this:
double radius;
//Create a Circle object
Circle myCircle = new Circle();
System.out.print("Enter a radius: ");
radius = in.nextDouble();
myCircle.setArea(radius);
System.out.printf(" The area of this circle is: %.2f ",myCircle.getArea());
}
The subclass would look like this:
public class Circle
{
double area;
//Set the area
private void setArea(double r){
area = r * r * Math.PI;
}
//Return the area
private double getArea(){
return area;
}
Explanation / Answer
CircleTest.java
import java.util.Scanner;
public class CircleTest {
public static void main(String[] args) {
double radius;
//Create a Circle object
Scanner in = new Scanner(System.in);
Circle myCircle = new Circle();
System.out.print("Enter a radius: ");
radius = in.nextDouble();
myCircle.setArea(radius);
System.out.printf(" The area of this circle is: %.2f ",myCircle.getArea());
}
}
Circle.java
public class Circle
{
double area;
//Set the area
public void setArea(double r){
area = r * r * Math.PI;
}
//Return the area
public double getArea(){
return area;
}
}
Output:
Enter a radius: 5
The area of this circle is: 78.54
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.