i have one doubt in mind that….
1) we can call & access any static method or variable from any non static method but from static method we can not access any non static method or variable…..why.
2) but we can create a instance of any class from static method.
please tell me the reason to understand better answer of my question.
class Class1
{
static int x=0;
int w = 0;
private static Class2 test()
{
w = 88; // give error because w is not a static member.
test1(); // give error because test1() is not a static function.
Class2 z = new Class2(); // here i am creating instance of class2
return z;
}
private int test1()
{
x = 9;
return x;
}
}
class Class2
{
}
thanks
To understand the reason why you’d first have to understand the difference between a
classand an actualobject.I can define a class like the following:
What i will be telling the compiler by this is what a
Carwould look like if i where to create such a thing. NoCaris created at this point but the computer has an understanding of what a car is. We have given it a blueprint. This is called aclassNext i can go and actually create a car:
Now
myCarcontains an actualobjectand i told the computer it is a car. I also created another car inotherCar. These are both individual objects. and both have their ownNamebelonging to the object.So now we have 2 objects but still only 1 class.
Now sometimes the need may arise for
propertiesofmethodsthat have some link to the conceptCarbut don’t require a specificCarto work on. in C# we can define such members using thestatickeyword.We can add the following
methodto our class:To actually find the first car that was ever build we do not need access to a specific car. we will try to find a car here but we don’t start out with one. so we mark it
static. this also means that we have to access toBrandof the car since we have noobjectto get it from. The case might even be that noCarat all was ever created in wich case the method can just returnNull. No car has ever existed and you don’t need one to find that out.the same goes for static fields and properties:
This field can store 1 car and 1 only. no matter how many cars you create. it’s value is tied to the class and not the object. So if
myCarwill store a value in this field thenotherCarcan read this same value.Consider the following example to sum it all up: