Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods in OOP

Tags:

oop

static

I've always known what static methods are by definition, but I've always avoided using them at school because I was afraid of what I didn't know.

I already understand that you can use it as a counter throughout your entire project.

Now that I am interning I want to know when exactly static methods are used. From my observation so far, static classes/methods are used when it contains a lot of functions that will be used in many different classes and itself doesn't contain too many critical local variables within the class where it is not necessary to create an instant of it.

So as an example, you can have a static class called Zip that zips and unzips files and provide it to many different classes for them to do whatever with it.

Am I right? Do I have the right idea? I'm pretty sure there are many ways to use it.

like image 279
user1542422 Avatar asked Jan 29 '16 16:01

user1542422


1 Answers

Static functions are helpful as they do not rely on an instantiated member of whatever class they are attached to.

Static functions can provide functionality related to an a particular class without requiring the programmer to first create an instance of that class.

See this comparison:

class Numbers
{
    public int Add(int x, int y)
    {
        return x + y;
    }

    public static int AddNumbers(int x, int y)
    {
        return x + y;
    }
}

class Main
{
    //in this first case, we use the non-static version of the Add function
    int z1 = (new Numbers()).Add(2, 4);

    //in the second case, we use the static one
    int z2 = Numbers.AddNumbers(3, 5);
}
like image 172
Addison Schuhardt Avatar answered Nov 15 '22 11:11

Addison Schuhardt