I tried to initialize an circle object from my test class, but the parameter(5.5) did not pass. The result is wrong. I tried to debug and find out the radius is 0.00 in circle class, 5.5 did not pass into the Circle class.
Anyone can help me with that?
This is my output:
The area of circle is: 3.14
This is my test class:
public class ShapeTest {
public static void main(String[] args){
Circle circle = new Circle(5.5);
System.out.println(circle);
}
}
}
This is my circle class:
public class Circle extends TwoDimensionalshape {
private double radius;
public Circle(double radius){
super(radius);
}
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
@Override
public double getArea(){
return 3.14+getRadius()+getRadius();
}
@Override
public String toString(){
return String.format("%s %,.2f%n ","The area of circle is: ",getArea());
}
}
This is my super class:
public class TwoDimensionalshape implements Area{
private double radius;
private double base;
private double height;
public TwoDimensionalshape(double radius){
this.radius = radius;
}
public TwoDimensionalshape(double base, double height){
this.base = base;
this.height = height;
}
public double getRadius() {
return radius;
}
public double getBase() {
return base;
}
public double getHeight() {
return height;
}
@Override
public double getArea(){
return 1;
}
public String toString(){
return "The area is: "+getArea();
}
}
Solution:
Your radius variable in Circle hides the radius variable in TwoDimensionalshape. They are 2 different variables. Your constructor sets the one in TwoDimensionalShape, but getArea is using the one in Circle.
Remove the radius variable in Circle. Let Circle inherit getRadius by removing that method from Circle. Also in Circle, move setRadius to TwoDimensionalShape.
Also, in getArea, multiply the radius twice instead of adding it twice. You can also use Math.PI instead of 3.14.
return Math.PI * getRadius() * getRadius();