Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
619 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...