Results 1 to 2 of 2
  1. #1
    csanch11 is offline Member
    Join Date
    Oct 2013
    Rep Power

    Default Using static methods

    I just wanted to get your opinion on my statement about static methods to see if I have a good grasp on it.

    - Static methods belong to the class and not a specific object of that class. Static methods are convenient to use because they can be called directly from the class whenever you need them. It is appropriate to use static methods when you know that a function of the method will not change throughout the class hierarchy or across instances. An example would be a class named Metric that converts distance in miles to kilometers. In the Metric class you have two defined static methods, milesToKolometers and kilometersToMiles, both returns a converted value in their respected units. In this class there is no need to collect and store any data. The class's sole purpose is to convert miles to kolometers and vice versa. Thus it would be reasonable/appropriate to make those methods static.

    Does that sound right to you? Would you add anything else to that statement?

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: Using static methods

    Quote Originally Posted by csanch11 View Post
    Static methods are convenient to use because they can be called directly from the class whenever you need them.
    I disagree with that simply because you can easily call a static or non-static from a class. Now if you are calling a static method of a foreign class you don't have to instantiate the foreign class.

    But in general I tend to always use static methods if if no object state is involved in the method (i.e. no instance fields are directly accessed). This means that a static method may just do some calculations as you described or modify objects passed to it. The method may or may not return a value.

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 1
    Last Post: 07-12-2012, 11:04 PM
  2. Replies: 2
    Last Post: 07-12-2012, 11:04 PM
  3. Replies: 8
    Last Post: 04-16-2012, 11:00 PM
  4. Replies: 1
    Last Post: 10-23-2011, 12:37 PM
  5. Static and non static class methods question
    By silverglade in forum New To Java
    Replies: 2
    Last Post: 05-14-2011, 10:10 PM

Posting Permissions

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