jcm
jcm

Reputation: 5659

Scala Singleton objects

I have the following question:

Define an Origin object that extends java.awt.Point. Why is this not actually a good idea? (Have a close look at the methods of the Point class.)

import java.awt.Point

object Origin extends Point { }

But I really don't know why it's not a good idea to extend this class. Could someone enlighten me please?

Upvotes: 2

Views: 273

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

The "contract" of Java Point is here: http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html. Point is designed to be mutable as noted by @Jesper and has mutators like setLocation(<overloaded>). Given this information here are the disadvantages of using it like this and using it at all:

  • It's a mutable object which is even in Java is a thing to avoid.
  • When you are creating a singleton of the Point like this object Origin extends Point { } you can only have a single Origin object in the entire application (not going to talk about classloaders and their scope).
  • If your intention is to have only a single Origin object you should still protect yourself from mutability that Point comes with. Otherwise you are letting anybody change the origin.

I hope you see the contradiction by now: on one hand if you want to have a single origin in application and be able to reason about it you would want your origin never change (immutable). On the other hand if you don't want to have a single origin, then creating a singleton does not help at all.

Upvotes: 3

Related Questions