Skip to main content
added 286 characters in body
Source Link
radar
  • 605
  • 3
  • 11

It's because it'sEdit: When you call a staticstatic method. There's a reason compilers give warnings when you do something like a.staticMethod() , whether through an instance or at the class- you arelevel, the compiler will recognize it as static and therefore treat it at the class-level, not actually invokingobject-level. This means that the method on an instancewill have no knowledge of A, as the syntax is implyingstate of the object that the method was invoked from. So you are simply calling A's staticIf using an object to call the method, sincesuch as in your example, the compiler will therefore only be able to know which method to call, A or B, based on what that object was declareddeclared as type A. It does not matter thatIf it was instantiated as an object of somea different subclass it won't matter, because it is a static method, and it has no notion of objects. (Hopefully this makes senseSo, I feel like I didn't explainin your example, this is why it very well)will call A's static method rather than B's.

Hopefully this was clearer explanation that what I had before

It's because it's a static method. There's a reason compilers give warnings when you do something like a.staticMethod() - you are not actually invoking the method on an instance of A, as the syntax is implying. So you are simply calling A's static method, since the object was declared as type A. It does not matter that it was instantiated as an object of some subclass. (Hopefully this makes sense, I feel like I didn't explain it very well)

Edit: When you call a static method, whether through an instance or at the class-level, the compiler will recognize it as static and therefore treat it at the class-level, not object-level. This means that the method will have no knowledge of the state of the object that the method was invoked from. If using an object to call the method, such as in your example, the compiler will therefore only be able to know which method to call, A or B, based on what that object was declared as. If it was instantiated as a different subclass it won't matter, because it is a static method, and it has no notion of objects. So, in your example, this is why it will call A's static method rather than B's.

Hopefully this was clearer explanation that what I had before

Source Link
radar
  • 605
  • 3
  • 11

It's because it's a static method. There's a reason compilers give warnings when you do something like a.staticMethod() - you are not actually invoking the method on an instance of A, as the syntax is implying. So you are simply calling A's static method, since the object was declared as type A. It does not matter that it was instantiated as an object of some subclass. (Hopefully this makes sense, I feel like I didn't explain it very well)