how a function not being static can be used in main which is static
According to my knowledge, we can only use static data in a 开发者_开发知识库static function.
But, our main()
function is static - i.e. Public static void main
. How can we use other functions of some xyz class which is not static in our main function which is static?
Create an instance of the class you want to call non-static members on.
It's not a matter of "only being able to use static data in a static function" - it's a matter of requiring some way of getting to an instance in order to call an instance method of that type.
Now how you get an instance to call the method on depends on what you're trying to do. You may want to create a new instance - or perhaps an instance will have been passed in as a parameter, or is available some other way.
Typically you use instances for particular state - so which state are you interested in?
You create a instance of xyz class in static main function and then access non static functions.
It's not impossible to use instance methods in a static method. To use instance methods, you just need a reference to the instance.
When you are inside a non-static method, you implicitly have a reference to the instance, and you can also explicitly use the this
keyword. If you want to use instance methods of another instance, you still need a reference to that instance.
If you create an object in a static method (or in a non-static method for that matter), you can use its instance methods. Example:
// Create an object
StringBuilder s = new StringBuilder();
// Use an instance method
s.Append(42);
// And another
string x = s.ToString();
You can instantiate new instance of Xyz in a static function and call its methods. however from a static method you cannot access non-static methods in the same class.
I think you are getting confused. You cannot reference instance variables/methods from within a static method of the same class via 'this' (as there is no reference to 'this'). You can create instances of other classes and reference their public instance variables/methods, etc. within a static method, as was previously mentioned. You can also pass an object as a parameter to a static method and do the same.
精彩评论