Online Course Discussion Forum

APCSA chapter 4 question 8

APCSA chapter 4 question 8
WangJialin - 2022年06月24日 Friday 22:16

The screenshots of the code are attatched.

The code works fine if "static" is added to getArea but doesn't work if not and an error message "Cannot make a static reference to the non-static method getArea(int) from the type Circle" pops up.

I think it's because I haven't created an instance of the class getArea, but i'm not sure how to do so with primitive data types, or is the problem something else?


WangDr. Kevin的头像
Re: APCSA chapter 4 question 8
WangDr. Kevin - 2022年06月25日 Saturday 17:17

The main() method is static, not part of any instance, and the getArea() method is not static, so it has to be invoked from an instance, like this: circle.getArea(radius). 

There are a few other problems.  The getRadius() method should return "radius", not "r".  The getArea() method, as written, calculates the area of any general circle, not the current instance, so it may be better to use "radius" field to calculate, instead of taking an input argument "r".