Search code examples
javascalaoopstatic-methodslanguage-concepts

Why aren't static methods considered good OO practice?


I'm reading Programming Scala. At the beginning of chapter 4, the author comments that Java supports static methods, which are "not-so-pure OO concepts." Why is this so?


Solution

  • One reason that static methods aren't very OO that hasn't been mentioned so far is that interfaces and abstract classes only define non-static methods. Static methods thus don't fit very well into inheritance.

    Note also that static methods do not have access to "super", which means that static methods cannot be overridden in any real sense. Actually, they can't be overridden at all, only hidden. Try this:

    public class Test {
        public static int returnValue() {
            return 0;
        }
    
        public static void main(String[] arg) {
            System.out.println(Test.returnValue());
            System.out.println(Test2.returnValue());
            Test x = new Test2();
            System.out.println(x.returnValue());
        }
    }
    
    
    public class Test2 extends Test {
        public static int returnValue() {
            return 1;
        }
    }
    

    When you run this, you won't get what you expect. Test.returnValue() gives what you expect. Test2.returnValue() hides the method of the same name in the superclass (it does not override it), and it gives what you would expect.

    One might naively expect "non-statically" calling a static method to use polymorphism. It doesn't. Whatever class the variable is declared as is the one used to look up the method. This is bad form because someone might expect the code to do something different from what it actually does.

    This doesn't mean, "Don't use static methods!" It does mean that you should reserve use of static methods for those instances where you really want the Class object to own the method, and not just as a lazy way of making a singleton.