Question

A friend of mine asked me whether he can override a static variable in Java and I was shocked that he even thought about such a weird way of coding. Then he explained me that this is possible in PHP and I want to know whether there are a good reasons why a good developer should do that. In my opinion static members are characterized as class members and not related to an object and therefore they are not related to derivation of classes, but I cannot convince him as he is so naive and stubborn.

Can anyone give either a good argument against this whole thing or convince me that this is a cool feature?

Was it helpful?

Solution

The static inheritance does not make any sense. It is not that it is not possible, just that you get no benefit from it.

With normal inheritance you get the benefit of having a different implementation for the same thing and not knowing/caring which implementation will be used. With static inheritance you don't have an object to operate with and you are using a class name, so you cannot take advantage of polymorphism.

E.g. if you are calling Child.someMethod() you are tied to implementation of the child and if you actually just need the parent, you can just do Parent.someMethod() instead. If you need to add something to Parent implementation, you just make a Child.someOtherMethod() where you call the parent and do some other things after. The static inheritance is just syntactic sugar...

OTHER TIPS

As far as I know, the static keyword in Java is used to define Class variables. A Class variable has one instance for all Objects of that class. So in Java you can not override a static variable, it doesn't make sense. Any changes done to a static variable in one Class propagates to another class. This is what static is used for, in JAVA.

This is the same way IT SHOULD WORK in PHP (I am not really a PHP expert), but if your friend can provide code showing that a static variable in PHP was overridden and the variable has a different value that from another class, I will be very glad.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top