Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By Sierra

Thread: static methods

  1. #1
    cups is offline Member
    Join Date
    Dec 2011
    Posts
    14
    Rep Power
    0

    Default 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.

    Java Code:
    public double abs() {
         return Math.sqrt((this.real*this.real + this.imag*this.imag));
    }
    and
    Java 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

  2. #2
    Sierra is offline AN21XX
    Join Date
    Mar 2012
    Location
    Munich
    Posts
    297
    Rep Power
    3

    Default 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
    wsaryada likes this.
    I like likes!

Similar Threads

  1. Replies: 8
    Last Post: 04-16-2012, 11:00 PM
  2. Replies: 1
    Last Post: 10-23-2011, 12:37 PM
  3. Static and non static class methods question
    By silverglade in forum New To Java
    Replies: 2
    Last Post: 05-14-2011, 10:10 PM
  4. Recursion with static and non static methods
    By sh4dyPT in forum New To Java
    Replies: 14
    Last Post: 03-27-2009, 06:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •