0

I have two seperate classes, one where i actually do the calculation of the area of a square like the first bit below, and one where I display the result but the one were i display the result is giving me an error saying that it can't find the "computeSquareArea" symbol. Why is it doing this and not transferring between classes?

public double computeSquareArea(double length)
{
    return length * length;
}


double sqArea = computeSquareArea(length);
System.out.println("Area of the square is " + sqArea);
2
  • 1
    Call your function with objects I guess. Commented Feb 14, 2017 at 3:05
  • show your entire class. Commented Feb 14, 2017 at 3:17

2 Answers 2

1

Non-static methods belong to the instance of the object, while static methods belong to the class.

In your code, computeSquareArea() is a non-static method. This means that in order to call it, you must call it on an instance of the class that it is in.

If you want to be able to call the method without requiring an instance first, you can use a static method. In order to make the method static, change public double computeSquareDistance() to public static double computeSquareDistance()

You can read more about this here.

Sign up to request clarification or add additional context in comments.

3 Comments

even after adding the static im having the same issue. Do i have to construct an object in my other class in order to use it in the first one?
Let's say computeSquareArea() is in a class called Foo. In order to call the method from another class, you should call Foo.computeSquareArea(). If this isn't working for you, try posting the actual code, so we can further help you.
The issue isn't really static vs. non-static. You need to call the method appropriately. If it's static, the appropriate way is className.methodName(). If it's not static, the appropriate way is instanceRef.methodName(). If you call simply methodName(), the method must be defined in the same class where the call occurs.
1

As I can see, your method computeSquareArea(double length) is not static. So I guess you need to Intantiate the class that have your method computeSquareArea(double length). Like for Example, lets assume your Class Name is SomeClass.

SomeClass someClass = new SomeClass();
double sqArea = someClass.computeSquareArea(length); // This would be the method of your newly created Instance of SomeClass
System.out.println("Area of the square is " + sqArea);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.