static method


Static methods (also known as class methods) can be called without having to instantiate the class that houses the static method. 

For example, here we have a public class EnumTesterClass with a public static method “TestEnums”

public class EnumTesterClass
{
    public static void TestEnums()
    {
     //some content here

    }
}

Now, suppose I need to call the TestEnums method from another class.  Since the method is static all I need to do is specify the namespace and the name of the class to access the method:

image

Now look at what happens when I actually instantiate the EnumTesterClass.  The static method “TestEnums” can not be accessed:

image

Now let’s see what happens when I remove the static keyword from the TestEnums method (thus making it an instance method):

public class EnumTesterClass
{
    public void TestEnums()
    {
     //some content here

    }
}

Now the method is no longer available by specifying the namespace and the name of the class:

image

The method is only available if we actually instantiate the class:

image

As we can see static methods can only be accessed from specifying the name of the class.  They can not be accessed from an instance of the class.

So when should we use static methods as opposed to instance methods?

Use static methods when the outcome of the method will not change based on the state of the instance of the object.  Recall that Static methods are also known as Class methods.  This is because they pertain to the class itself not to an instance of the class.   (That is why methods that are non-static are known as instance methods because they depend on and pertain to an instance of the class.)

No comments:

Post a Comment