ericyoung
ericyoung

Reputation: 641

Why can non-static method access static field?

I know that static method cannot access fields that are instance fields, What it confuses me is: why non-static method can access static filed currentID? In the code below, currentID is static field, getNextID is a static function. Surprisingly, it passes the compilation without error.

 public class WorkItem
{
// Static field currentID stores the job ID of the last WorkItem that 
// has been created. 
private static int currentID;

//Properties. 
protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }

public WorkItem()
{
    ID = 0;
    Title = "Default title";
    Description = "Default description.";
    jobLength = new TimeSpan();
}

// Instance constructor that has three parameters. 
public WorkItem(string title, string desc, TimeSpan joblen)
{
    this.ID = GetNextID();
    this.Title = title;
    this.Description = desc;
    this.jobLength = joblen;
}

// Static constructor to initialize the static member, currentID. This 
// constructor is called one time, automatically, before any instance 
// of WorkItem or ChangeRequest is created, or currentID is referenced. 
static WorkItem()
{
    currentID = 0;
}


protected int GetNextID()
{
    // currentID is a static field. It is incremented each time a new 
    // instance of WorkItem is created. 
    return ++currentID;
}

}

Upvotes: 1

Views: 2911

Answers (1)

Joey
Joey

Reputation: 354406

Static fields are often used for compile-time constants, so it makes sense to make access to them painless. Thus they are accessible from instances of their enclosing type.

Besides, a static member cannot reference an instance member for obvious reasons (it is not associated with an instance, but only with a type). But vice-versa is no problem as an instance usually knows its own type and thus can look up static members as well.

Upvotes: 5

Related Questions