Java made a restriction that there
could be only one superclass for any
class, but there could be many interfaces implemented by each new class
defined, and that would give many of
the benefits of polymorphism without
the associated issues.
In the time since Java was created
(and even in some cases before that),
another strategy known as mixins provided a safer alternative to full multiple
inheritance. Mixins are like Java interfaces that can still have behavior defined
on them. Any given class still has only
one actual superclass, but it can also mix
in other, richer aspects, providing more
value than just interface definitions
(which then need to be satisfied with
code implementations).
Scala calls these traits, and it has good
support for them. Surprisingly, they
work just fine in the JVM, even though
the JVM was never designed to support
them. Behind the scenes, both an interface and a class with the behavior and
state necessary are created when you
define a trait, and a clever hookup by the
compiler makes the whole thing work
pretty well. Listing 3 shows an example
of traits in Scala.
And here’s an example of use:
The class Frog has only one actual
superclass, but it mixes in the Green and
HasLegs traits. The HasLegs trait brings
with it the need to supply a number of
legs before the class can be instantiated,
so this is filled in when we define the
Frog class.
abstract class Amphibian {
def color: String
def swims = true
def breathes = true
}
trait Green {
def color = "Green"
}
trait HasLegs {
def legs: Int
def move = println("I move using %d legs".format(legs))
}
class Frog extends Amphibian with Green with HasLegs {
val legs = 4
}
COMMUNITY
JAVA IN ACTION
See all listings as text
scala> val kermit = new Frog
kermit: Frog = Frog@1dfe1a
scala> kermit.move
I move using 4 legs
scala> kermit.color
res2: java.lang.String = Green
scala> kermit.swims
res3: Boolean = true
Implicit Manifests
The final features we are going to look
at in this article are, on the surface, not
apparently linked. In fact, they are linked
by a JVM shortcoming: type-safe erasure
and the lack of reified types.
When Java was first created, it had
a rich set of collections (a novelty for a
language at the time, when it was con-
sidered normal to write your own col-
lections or buy a library such as Rogue
Wave in C++). The problem was that
while Java was strongly typed, collections
ignored the type, so when you asked
for an ArrayList you got an ArrayList that
could hold anything. Until generics were
added in Java 5, you had to test and/or
cast the type of objects you got out of a
collection before you could use them as
that type.
ABOUT US
blog