Hi friends,
I want to know that What is the difference between static and instance methods?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Mar 13, 2012, 8:39 AM EDT
Static methods do not refer to a particular instance but refer to the class or struct as a whole.
When called from outside their containing class or struct, instance method are always preceded by a reference to the instance to which they refer. However, static methods are always preceded by the class or struct name.
When called from within their containing class or struct, an instance method can be optionally preceded by 'this' and a static method can optionally be preceded by the class or struct name.
Sam HobbsRank #107 · 20.5K reputationPosted Mar 14, 2012, 4:54 AM EDT
pagefault pagefault12 reputationPosted Mar 14, 2012, 10:29 AM EDT
One can think of 'static' code as like traditional non object oriented code. C, FORTRAN, BASIC ...
Static code (or variables) exists only in a single instance. Previous poster has a good point about semantics.
An example where a static variable is useful is this:
Imagine one wants to instantiate multiple objects of a certain class but let each have a unique serial number. Let the object type be a car:
public class Car
{
string make;
string model;
static int serial = 0;
// constructor
public Car (string make, string model)
{
this.make = make;
this.model = model;
carId = serial++;// assign unique Id no, increment serial
}
}
On each instantiation of Car:
Car car = new ("Ferrari","Testarossa");
the static 'serial' which only exists in a single place will count up and give each new object a unique id.
brunda kRank #3,804 · 389 reputationPosted Mar 14, 2012, 12:52 PM EDT