Question: Question:
It is said that static methods cannot be overridden in Java.
For example, the following code is not considered to be an override.
(It is said to be hiding, not override)
class A {
public static void a() {
System.out.println("A.a()");
}
}
class B extends A {
public static void a() {
System.out.println("B.a()");
}
}
Meanwhile, let's write similar code in Python.
class A(object):
@staticmethod
def a():
print("A.a()")
class B(A):
@staticmethod
def a():
print("B.a()")
Is this an override?
question:
- Should the above Python code example be considered an override? What is the rationale for that decision?
- What about classmethods and regular methods instead of staticmethods?
- What should you think in a dynamic language in general?
Answer: Answer:
It's a bit rough answer, but please use it as a link until you get a better answer.
Should the above Python code example be considered an override? What is the rationale for that decision?
You can think about it. In the following code, I added an instance method call_a()
that calls the static method a()
to the base class A
, and when I call call_a ( call_a()
of the instance of B
, Ba()
is executed. This is the basis.
class A(object):
@staticmethod
def a():
print("A.a()")
def call_a(self):
self.a()
class B(A):
@staticmethod
def a():
print("B.a()")
p = B()
p.call_a() # B.a()
What about classmethods and regular methods instead of staticmethods?
classmethod
with the class method in a similar way. Ordinary methods can, of course, be considered overrides.
What should you think in a dynamic language in general?
Going back to the basics of OOP, "overriding" means "changing = overriding existing behavior for a message".
The first example is just to confirm that, if call_a()
also calls Aa()
on an instance of B, this means that the behavior could not be changed, so it cannot be overridden. That's why.