Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to have a non static method which does not use an instance variable?

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.

like image 527
Chiseled Avatar asked Aug 04 '15 16:08

Chiseled


People also ask

Can you call a non-static method without an instance?

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.

Can non-static methods access instance variables?

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.

When would you use a non-static method?

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.

Why static methods does not allow non-static variables?

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.


1 Answers

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!).

like image 76
Jashaszun Avatar answered Sep 25 '22 11:09

Jashaszun