Physics, asked by gogamer5846, 1 year ago

Can non-static method be called from a static method?

Answers

Answered by Elwin123
0
Because a static field/method--by definition--is not tied to any single object/instance of the class, while a non-static field/method always refers to an actual object/instance in some way.

Since that probably sounded too vague/abstract to answer the question, and this kind of confusion usually stems from a misunderstanding of what static actually means, let's make this concrete with some C++-like pseudocode:

class Foo { public: static int a() { return 2; } int b() { return d_x; } Foo(int x) { d_x = x; } private: int d_x; }

The static method a is not tied to any particular instance of Foo, meaning it can be called from anywhere, whether or not you have an actual Foo object. In C++ you'd simply write Foo::a(), and it would always return 2.

The non-static method b is tied to a single instance of Foo. Because it simply returns the int inside a given Foo object, it doesn't make any sense to try calling b() without a specific Foo object. What would you expect it to return if it didn't have a Foo? So Foo f; f.b(); makes sense but Foo::b()does not.

If I tried to make a() call b(), then whenever I called a() without an actual instance of Foo, I'd also be calling b() without an actual instance of Foo, so now a() doesn't make sense either.

Essentially, the two methods are implemented something like this:

namespace Foo { int a() { return 2; } int b(Foo* this) { return this->x; } };

When you look at the methods this way, it's fairly obvious why b() can call a() but not the other way around: a() simply doesn't have a Foo* lying around to give to b().

Incidentally, you can "work around" this limitation by writing a static method that takes an actual Foo object and then calls non-static methods on that Foo object. But that's usually a code smell indicating that you have static methods which shouldn't be static or non-static method that should be static, or a class that's trying to do too many things at once.


Elwin123: no it cannot be called
utkarsh910: Hut pagal
Similar questions