Suppose that I have a Java class with a static method, like so:
class A { static void foo() { // Which class invoked me? } }
And suppose further that class A has an arbitrary number of subclasses:
class B extends A { } class C extends A { } class D extends A { } ...
Now consider the following method invocations:
A.foo(); B.foo(); C.foo(); D.foo(); ...
My question is, how can method foo()
tell which class is invoking it?
Invoking a public static Method After we have the class instance, we can get the public static method object by calling the getMethod method. Once we hold the method object, we can invoke it simply by calling the invoke method.
A static method is not part of the objects it creates but is part of a class definition. Unlike instance methods, a static method is referenced by the class name and can be invoked without creating an object of class.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name.
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class.
The static method cannot invoke the instance member as well as methods of the class. Because static methods are accessed without the object reference of the class but we cannot access the instance variables and method without an object reference.
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It's definition is immutable via inheritance. @classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance.
It can't, and that's part of the problem with static methods. As far as the compiler is concerned A.foo()
and B.foo()
are exactly the same thing. In fact, they compile down to the same bytecode. You can't get more similar than that.
If you really need this sort of information, use a singleton and turn foo()
into an instance method. If you still like the static syntax, you can build a facade A.foo()
.
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