Static methods, can only be accessed by Class because those are not instance level methods.Refer to the highlighted text in the code below. In order to access static methods the syntax is <ClassName>.<methodName>
When to use? Static methods are good for utility methods that do not depend on a particular instance.
Restrictions:
1. Why cannot static methods access non-static variables (except by creating an instance within static method)?
A static method is associated with the class, so it cannot access any non-static variables. It would not know which instance's non-static variables to use.
2. Why this operator cannot be used in static method?
"this" implies an object/instance that is the reason this operator cannot be used in static method.
When to use? Static methods are good for utility methods that do not depend on a particular instance.
Restrictions:
- Static methods cannot access non-static variables. If at all this is done, it will lead to compile time error.
- "this" operator cannot be used in static methods.
- In order to set non-static variables, an instance needs to be created within the static methods. However, this would not make any sense as the object scope would be only in the static method.
1. Why cannot static methods access non-static variables (except by creating an instance within static method)?
A static method is associated with the class, so it cannot access any non-static variables. It would not know which instance's non-static variables to use.
2. Why this operator cannot be used in static method?
"this" implies an object/instance that is the reason this operator cannot be used in static method.
No comments:
Post a Comment