-
static methods
Hey there,
so I had to write a method and an equal static method that returns the absolute value of an complex number.
I know how to do it and it works fine, but I was wondering why I should use the static method.
I've googled it and found out that it is used for operations that refer on the class, not on an particular object.
Code:
public double abs() {
return Math.sqrt((this.real*this.real + this.imag*this.imag));
}
and
Code:
public static double abs(Complex zahl) {
return zahl.abs();
}
So difference: I have to commit the number I want to operate on and I cannot use
the attributes from it in this method. So I just call the method that can.
Is this the difference? Or what can I not see?
B/c I was wondering why would you do it then? I mean, why is it important to call a method
with an object AND call it from an object aswell?
regards,
cups
-
Re: static methods
For the non-static method you need to create an object of that class. If the method is independant of an objects attributes it is wise to make it static as you do not have to create an object each time you need to use it. Typical examples are conversion methods that just convert one type to another and that are related to the containing class. If the method uses attributes of the object it is wise to have it inside the object that you need anyway.
In your example:
- If the containing class is the class DoubleContainer and contains a double value, it would be wise to make the abs() method non-static and apply it to the internally stored value.
- If your containing class is the class BasicMathOperations, it is not intended to contain a double value. Here you make it static so everyone may use it