result will be "From B"
Private or static method that call from another method chosen by class that originally declare caller private or static method? Right?
As I see from the code, replacing 'static' modifier to 'private' will lead to the same results. But the reason for both cases is different. I have replaced 'static' modifier into 'private' and got instance methods:
The overriden method in class 'B' is commented. Hence, the new instance of 'B' will call inherited method 'meth()'. Private method 'privateMeth()' of class 'A' is not inherited by class 'B' as it is private. But method A.meth() does something. Its behavior was exposed to private helper method A.privateMeth(). But when the method A.meth() is overriden in 'B', this overriding class 'meth()' relies on his own functionality, therefore it may have its own private methods. Names of these private methods can be the same as of class 'A', but they are not either hidden or overriden.
And it in case with 'static' modifiers, static method of class 'B' hides static method of class 'A'.
Sergej Smoljanov wrote:// if you changed static to private
//or add private to staticMeth in A, you can not mark as static
This code defined a private static method in A, and in class B you can have a static method with the same name without any problem. The following code compiles!
This is the code of your other suggestion (replacing static with private in class A) and again this code compiles successfully!
But if you have a static method (with at least default access in class A), you can not have an instance method in subclass B with the same method signature, as the following code illustrates:
The compiler error is:
staticMeth() in B cannot override staticMeth() in A
private void staticMeth() {
^
overridden method is static
1 error
The other way around is also not allowed. So if you have an instance method (with at least default access in class A), you can not have a static method in subclass B with the same method signature. Again illustrated in this code snippet:
You'll get a slightly different compiler error:
staticMeth() in B cannot override staticMeth() in A
private static void staticMeth() {
^
overriding method is static
1 error
i didn't see "shadowing" mentioned, which is the way to explain what you're seeing. Static methods aren't overridden, they're shadowed. Polymorphism is only for overridden methods, nothing else. If you remove static in both cases, you'll eliminate the shadow and create an override in its place it will be polymorphism going for the win!
Post by:autobot
and POOF! You're gone! But look, this tiny ad is still here:
a bit of art, as a gift, the permaculture playing cards