The compiler does not let a static method call a non static method. I understand it does this because a not static method usually ends up using an instance variable.
But does it make sense to have a non static method which does not use an instance variable. If we have a behavior which does not affect or isn't affected by the instance state , shouldn't such a method be marked as static.
In a non-static method, the method use runtime or dynamic binding. So that we cannot access a non-static method without creating an instance.
We cannot access non-static variables or instance variables inside a static method. Because a static method can be called even when no objects of the class have been instantiated.
A non-static method can access any static method without creating an instance of the class. A non-static method can access any static variable without creating an instance of the class because the static variable belongs to the class.
Non-static variables are part of the objects themselves. To use a non-static variable, you need to specify which instance of the class the variable belongs to. ... In other words, non-static data cannot be used in static methods because there is no well-defined variable to operate on.
Well sure! Let's assume that you have in interface IMyCollection
. It has a method boolean isMutable()
.
Now you have two classes, class MyMutableList
and class MyImmutableList
, which both implement IMyCollection
. Each of them would override the instance method isMutable()
, with MyMutableList
simply returning true
and MyImmutableList
returning false
.
isMutable()
in both classes is an instance method that (1) does not use instance variables, and (2) does not affect instance state. However, due to constraints in the language (it's impossible to override static methods), this design is the only practical one.
Also, I would like to clear up a misconception (as @manouti did as well): non-static methods aren't instance because they use any instance variables or affect instance state; they're instance methods because they were defined that way (without the static
keyword), and thus have an implicit this
parameter (which, in languages like Python, is actually explicit!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With