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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
brunda kPosted Mar 14, 2012, 4:52 PM
pagefault pagefaultPosted Mar 14, 2012, 2:29 PM
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.
Sam HobbsPosted Mar 14, 2012, 8:54 AM
VulpesPosted Mar 13, 2012, 12:39 PM
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.