In the past more than 10 years, the elements of object-oriented language design have been the core of inheritance. Languages that do not support inheritance, such as Visual Basic, are ridiculed as "toy languages" and are not suitable for real work. At the same time, the support methods used to support inherited languages are diverse, leading to many controversies. Is multiple inheritance really necessary (as the creator of C + + has identified), is it unnecessary and ugly (as the creators of C # and Java believe)? Ruby and Scala are two newer languages that take a method of multiple inheritance-as I discussed in the last issue of Scala's features (see Resources).
Like all outstanding languages, Scala also supports implementation inheritance (see Resources). In the Java language, a single implementation inheritance model allows you to extend base classes, add new methods and fields, and so on. Despite some syntactic changes, Scala's implementation inheritance is still similar to the implementation in the Java language. The difference is that Scala blends the design of objects and functional languages, which is well worth discussing in this installment.
Common Scala Objects
Like the previous articles in this series, I'll use the person class as a starting point to explore Scala's inheritance system. Listing 1 shows the class definition for person:
Listing 1. Hey, I'm a human.
// This is Scala
class Person(val firstName:String, val lastName:String, val age:Int)
{
def toString = "[Person: firstName="+firstName+" lastName="+lastName+
" age="+age+"]"
}
Person is a very simple poso (Common Scala object, Plain old Scala objects) with three read-only fields. You might recall that to make these fields readable and writable, you can simply change the Val in the primary constructor declaration to Var
In any case, it is also very simple to use the person type, as shown in Listing 2:
Listing 2. Personapp
// This is Scala
object PersonApp
{
def main(args : Array[String]) : Unit =
{
val bindi = new Person("Tabinda", "Khan", 38)
System.out.println(bindi)
}
}
It's not a surprising code, but it gives us a starting point.