Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Static Method vs. Instance Method

Status
Not open for further replies.

sds814

Programmer
Feb 18, 2008
164
US
I was reading this statement:

"Difference is that instance methods have access to both the instance fields of the object instance and the static fields of the class, whereas static methods don’t have access to instance fields or methods."

I wanted to understand this with an example so I wrote this code:
Code:
    public class A
    {
        public int InstanceField = 4;
        public static int StaticField = 5;
    }

    public class Program
    {
        static void StaticMethod()
        {
            A a = new A();
            int InstanceField = a.InstanceField;
            int StaticField = A.StaticField;
        }

        void InstanceMethod()
        {
            A a = new A();
            int InstanceField = a.InstanceField;
            int StaticField = A.StaticField;
        }
    }
Based on the statement I thought I couldn't have an instance of class A and an instance of the field InstanceField in the StaticMethod of class Program. There were no compile or run-time errors.

I'm pretty sure I haven't understood the statement correctly.
 
a is an instance of A so gives you access to Instance fields of that class.

What the statement is trying to say is that you cannot access non static fields of an object without an instance of that object, (so A.Instance field would generate a compiler error), but you can access static fields from instances so a.StaticField is legitimate.

Rhys

"Technological progress is like an axe in the hands of a pathological criminal"
"Two things are infinite: the universe and human stupidity; and I'm not sure about the the universe"
Albert Einstein
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top