36

In Programming in Scala: A Comprehensive Step-by-Step Guide, the author said:

One way in which Scala is more object-oriented than Java is that classes in Scala cannot have static members. Instead, Scala has singleton objects.

Why is a singleton object more object-oriented? What's the good of not using static members, but singleton objects?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sawyer
  • 15,581
  • 27
  • 88
  • 124

7 Answers7

59

Trying for the "big picture"; most of this has been covered in other answers, but there doesn't seem to be a single comprehensive reply that puts it all together and joins the dots. So here goes...

Static methods on a class are not methods on an object, this means that:

  1. Static members can't be inherited from a parent class/trait
  2. Static members can't be used to implement an interface
  3. The static members of a class can't be passed as an argument to some function

    (and because of the above points...)

  4. Static members can't be overridden
  5. Static members can't be polymorphic

The whole point of objects is that they can inherit from parent objects, implement interfaces, and be passed as arguments - static members have none of these properties, so they aren't truly object-oriented, they're little more than a namespace.

Singleton objects, on the other hand, are fully-fledged members of the object community.


Another very useful property of singletons is that they can easily be changed at some later point in time to not be singletons, this is a particularly painful refactoring if you start from static methods.

Imagine you designed a program for printing addresses and represented interactions with the printer via static methods on some class, then later you want to be able to add a second printer and allow the user to chose which one they'll use... It wouldn't be a fun experience!

Kevin Wright
  • 49,540
  • 9
  • 105
  • 155
  • 1) "Static members can't be overridden" -- can singleton members (members of singleton?) be overridden? 2) About printer problem -- how is it easier with singletons? – Aivar Jan 14 '11 at 19:01
  • More remarks about the printer problem -- as I see, it's easier with singletons only when the objects are really passed around, but I suspect usually they are accessed by their static name – Aivar Jan 14 '11 at 19:16
  • 1
    @Aivar In both cases, the singleton is a true type. Lifting methods from the singleton to a supertype (and using this supertype in variables/params) is therefore a relatively trivial operation. At which point, you can override and create other instances. – Kevin Wright Jan 14 '11 at 19:18
  • @KevinWright : Could you please explain the example of `printing addresses` ? – tharindu_DG Jan 17 '17 at 10:15
  • You have a `Printer` class, it has a bunch of static methods. You then need a second kind of printer, so you add a second class, also with static methods. How do you then abstract those two, allowing the original code to be used with either printer? Now imagine the `Printer` is a singleton. Because it's a true object, you can extract an interface (do this in an IDE, and it'll often update references to the singleton to also be refs to the new interface). Write your second printer as a singleton implementing the *same* interface. Job done! – Kevin Wright Jan 18 '17 at 11:59
12

Singleton objects behave like classes in that they can extend/implement other types.

Can't do that in Java with just static classes -- it's pretty sugar over the Java singleton pattern with a getInstance that allows (at least) nicer namespaces/stable identifiers and hides the distinction.

  • 3
    Given that the question was tagged "Scala", it's not actually correct that a Scala singleton implements the `getInstance` static method (nor could it, Scala doesn't have static methods...). Although it's true that the equivalent logic in Java would usually pick on this method name. – Kevin Wright Nov 06 '10 at 22:52
  • @Kevin Wright But (the useful) scalac compiles to the JVM -- and static methods/properties are JVM constructs underneath :-) The (top-level) objects must be stored somewhere. (Although your answer is much better.) –  Nov 06 '10 at 23:47
  • 1
    Of course; singletons are generated as classes with a single instance: For a singleton named `Foo`, the scala compiler will emit a class named `Foo$` that has a static field named `MODULE$` containing the one-and-only instance. As it also generates static forwarder methods in the `Foo` *class* - purely for the benefit of Java interop - you rarely need to see/touch any of this underlying mechanism. There is no *method* used to get the singleton, and certainly not one named `getInstance` – Kevin Wright Nov 08 '10 at 12:01
11

Hint: it's called object-oriented programming.

Seriously.

Maybe I am missing something fundamentally important, but I don't see what the fuss is all about: objects are more object-oriented than non-objects because they are objects. Does that really need an explanation?

Note: Although it sure sounds that way, I am really not trying to sound smug here. I have looked at all the other answers and I found them terribly confusing. To me, it's kind of obvious that objects and methods are more object-oriented than namespaces and procedures (which is what static "methods" really are) by the very definition of "object-oriented".

An alternative to having singleton objects would be to make classes themselves objects, as e.g. Ruby, Python, Smalltalk, Newspeak do.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 1
    Aren't classes objects in both Scala and Java? – Aivar Jan 14 '11 at 19:06
  • This is the best answer. – Above The Gods Jun 28 '20 at 22:09
  • @Aivar: No, they aren't. You cannot pass a class as an argument, you cannot store it in a variable or field or data structure, you cannot return it from a method. Both Scala and Java have a Reflection API that can give you an object that represents a *proxy* to a class, but that object is not the class itself. When you call a static method, there is no object involved. In fact, when you go down to the JVM-level, you will see that the byte code for calling a static method is actually different from the byte code for calling an instance method. – Jörg W Mittag Jun 29 '20 at 06:24
2

For static members, there is no object. The class really just is a namespace.

In a singleton, there is always at least one object.

In all honesty, it's splitting hairs.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
Yann Ramin
  • 32,895
  • 3
  • 59
  • 82
  • It's not splitting hairs when you must pass *something* implementing a `foo()` method as an argument, and all you have is a class with `static void foo...` - It's a recipe for some really bad design. – Kevin Wright Nov 06 '10 at 11:26
2

It's more object oriented in the sense that given a Scala class, every method call is a method call on that object. In Java, the static methods don't interact with the object state.

In fact, given an object a of a class A with the static method m(), it's considered bad practice to call a.m(). Instead it's recommended to call A.m() (I believe Eclipse will give you a warning). Java static methods can't be overridden, they can just be hidden by another method:

class A {
    public static void m() {
        System.out.println("m from A");
    }
}
public class B extends A {
    public static void m() {
        System.out.println("m from B");
    }
    public static void main(String[] args) {
        A a = new B();
        a.m();
    }
}

What will a.m() print?

In Scala, you would stick the static methods in companion objects A and B and the intent would be clearer as you would refer explicitly to the companion A or B.

Adding the same example in Scala:

class A
object A { 
  def m() = println("m from A") 
}
class B extends A
object B { 
  def m() = println("m from B")
  def main(args: Array[String]) {
    val a = new B
    A.m() // cannot call a.m()
  }
}
huynhjl
  • 41,520
  • 14
  • 105
  • 158
2

There is some difference that may be important in some scenarios. In Java you can't override static method so if you had class with static methods you would not be able to customize and override part of its behavior. If you used singleton object, you could just plug singleton created from subclass.

Community
  • 1
  • 1
Piotr Findeisen
  • 19,480
  • 2
  • 52
  • 82
-7

It's a marketing thing, really. Consider two examples:

class foo
   static const int bar = 42;
end class

class superfoo
    Integer bar = ConstInteger.new(42);
end class

Now, what are the observable differences here?

  • in a well-behaved language, the additional storage created is the same.
  • Foo.bar and Superfoo.bar have exactly the same signatures, access, and so on.
  • Superfoo.bar may be allocated differently but that's an implementation detail

It reminds me of the religious wars 20 years ago over whether C++ or Java were "really" Object Oriented, since after all both exposed primitive types that aren't "really" objects -- so, for example you can't inherit from int but can from Integer.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263