Object Oriented Programming in Scala - uni- · PDF fileClasses & Objects Composition &...
Transcript of Object Oriented Programming in Scala - uni- · PDF fileClasses & Objects Composition &...
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Object Oriented Programming in Scala
Heiko Bremer
Technische FakultatUniversitat Bielefeld
18. Juni 2014
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Heutige Agenda
Classes & ObjectsClasses, Fields and Methods / Singelton Objects
Composition & InheritanceAbstract classes, extending classes and overriding
Class HierarchyScala’s class hierarchy and inheritance
TraitsSimple code reuse with traits instead of multiple inheritance
Factory ObjectA factory object with privat subclasses and traits
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
Classes & Objects
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
Classes
Basic Information
I If you are familiar with Java, you’ll find the concepts in Scala aresimilar, but not exactly the same.
I A class is a blueprint for objects. Once you define a class, youcan create objects from the class blueprint with the keyword new
I Inside a class definition, you place fields and methods, which arecollectively called members.
I Fields, which you define with either val or var ,are variables that refer to objects.
I Methods, which you define with def , contain executable code.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
Classes
Code Example (⇒ Semicolon inference):In a Scala program, a semicolon at the end of a statement is usually optional.On the other hand, a semicolon is required if you write multiple statements on a single line
class Car {var speed = 0
def speedUp(s: Int): Unit = {speed += sprintln("Speed: "+ speed)
}}
val porsche = new Carporsche.speedUp(5)porsche.speed = 10
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
Singelton Objects
I One way in which Scala is more object-oriented than Java is thatclasses in Scala cannot have static members.
I Instead, Scala has singleton objects.I A singleton object definition looks like a class definition, except
instead of the keyword class you use the keyword object .I When a singleton object shares the same name with a class (in
the same source file), it is called that class’s companion object.I The class is called the companion class of the singleton object. A
class and its companion object can access each other’s privatemembers.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
Singelton Objects
Code Example:
object Car {def kw2ps(kw: Double): Double = { kw * 1.36}def ps2kw(ps: Double): Double = { ps / 1.36}
}
class Car {var speed = 0def speedUp(s: Int): Unit = {
speed += sprintln("Speed: "+ speed)
}}
println("100 kW sind " + Car.kw2ps(100) + " PS" )
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
Singelton Objects
I If you are a Java programmer, one way to think of singletonobjects is as the home for any static methods you might havewritten in Java. You can invoke methods on singleton objectsusing a similar syntax: SingletonObject.method
I A singleton object is more than a holder of static methods,however. It is a first-class object. You can think of a singletonobject’s name, therefore, as a name tag attached to the object
I One difference between classes and singleton objects is thatsingleton objects cannot take parameters. Because you can’tinstantiate a singleton object with the new keyword, you can’tpass parameters to its primary constructor.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
Singelton Objects
I A singleton object that does not share the same name with acompanion class is called a standalone object.
I You can use standalone objects for many purposes:I collecting related utility methods togetherI defining an entry point to a Scala application
I object Test {def testCar {println("\nNew Car:")val porsche = new Carporsche.speedUp(5)porsche.speed = 10porsche.speedUp(15)
}}
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
A Scala Application
I To run a Scala program, you must supply the name of astandalone singleton object with a main method that takes oneparameter, an Array[String] , and has a result type of Unit
I object Main {def main(args: Array[String]): Unit = {
Test.testCarprintln("100 kW sind " + Car.kw2ps(100) + " PS" )println("136 PS sind " + Car.ps2kw(136) + " PS" )
}}
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Classes, Fields and Methods / Singelton Objects
A Scala Application
I One difference between Scala and Java is that whereas Javarequires you to put a public class in a file named after the class
I However, it is recommended style to name files after the classesthey contain as is done in Java, so that programmers can moreeasily locate classes by looking at file names.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Composition & Inheritance
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Abstract classes
Basic Information
I A class with abstract members must itself be declared abstract,which is done by writing an abstract modifier in front of theclass keyword
I The abstract modifier signifies that the class may have abstractmembers that do not have an implementation. As a result, youcannot instantiate an abstract class.
I Unlike Java, no abstract modifier is necessary (or allowed) onmethod declarations. Methods that do have an implementationare called concrete.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Abstract classes
Basic Information
I Another bit of terminology distinguishes between declarationsand definitions.
I Class Vehicledeclares the abstract members model, tyres, spotand defines the concrete methods showModel, showTyres
I abstract class Vehicle {def model: Stringdef tyres: Intdef spotdef showModel { println("Model: " + model) }def showTyres { println("Reifen: " + tyres) }
}
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Extending classes
Basic Information
I To instantiate an Vehicle, therefore, we will need to create asubclass that extends Vehicle and implements the abstractmembers.
I Such an extends clause has two effects:I It makes classes Truck inherit all non-private members from
class VehicleI and it makes the type Truck a subtype of the type Vehicle.
I Class Truck is called a subclass of class Vehicle.Conversely, Vehicle is a superclass of Truck .
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Extending classes
Code Example:
abstract class Vehicle {def model: Stringdef tyres: Intdef spotdef showModel { println("Model: " + model) }def showTyres { println("Reifen: " + tyres) }
}
class Truck(mod: String, tyr: Int) extends Vehicle {def model: String = moddef tyres: Int = tyrdef spot { println("\nNew Truck ... ") }
}
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Using Override modifiers
Basic Information
I Scala requires the override modifier for all members thatoverride a concrete member in a parent class.
I The modifier is optional if a member implements an abstractmember with the same name
I The modifier is forbidden if a member does not override orimplement some other member in a base class.
I class Bike(mod: String) extends Vehicle {def model: String = moddef tyres: Int = 2def spot { println("\nNew Bike ... ") }override def showModel { println("Unser SuperBIKE: " + model) }
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Overriding methods and fields
Basic Information
I A difference is that in Scala, fields and methods belong to thesame namespace. This makes it possible for a field to override aparameterless method
I On the other hand, in Scala it is forbidden to define a field andmethod with the same name in the same class.
I Generally, Scala has just two namespaces for definitions in placeof Java’s four. Java’s four namespaces are fields, methods, types,and packages. By contrast, Scala’s two namespaces are:
I values (fields, methods, packages, and singleton objects)I types (class and trait names)
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Abstract classes, extending classes and overriding
Declaring final members
Basic Information
I Sometimes when designing an inheritance hierarchy, you want toensure that a member cannot be overidden by subclasses. InScala, as in Java, you do this by adding a final modifier to themember.
I abstract class Vehicle {def model: Stringdef tyres: Intdef spotfinal def showModel { println("Model: " + model) }final def showTyres { println("Reifen: " + tyres) }
}
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Scala’s class hierarchy and inheritance
Class Hierarchy
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Scala’s class hierarchy and inheritance
Scala’s class hierarchy
Basic Information
I In Scala, every class inherits from a common superclass namedAny .
I Because every class is a subclass of Any , the methods defined inAny are universal methods: They may be invoked on any object.
I AnyVal is the parent class of every built-in value class in Scala.I Scala also defines some intersting classes at the bottom of the
hierarchy, Null and Nothing ,which essentially act ascommon subclasses.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Scala’s class hierarchy and inheritance
Diagramm
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
What are traits?
I Traits are a fundamental unit of code reuse in Scala.I A trait encpasulates method and field definitions, which can then
be reused by mixing them into classes.
I Similar to interfaces in Java, traits are used to define object typesby specifying the signature of the supported methods.
I Unlike Java, Scala allows traits to be partially implemented; i.e.it is possible to define default implementations for somemethods. In contrast to classes, traits may not have constructorparameters.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
What are traits?
I A trait definition looks just like a class definition except that ituses the keyword trait
I trait Speed {private var speed = 0def showSpeed { println("Speed: "+ speed) }def speedUp(s: Int): Unit = { speed += s }def speedDown(s: Int) = { speed -= s }
}
trait Fuel {private var fuel = 0def showFuel { println("Fuel: "+ fuel) }def fuelUp(f: Int): Unit = { fuel += f }def fuelDown(f: Int) = { fuel -= f }
}
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
Traits mixed in
I Once a trait is defined, it can be mixed in to a class using thewith keyword.
I class Bike(mod: String) extends Vehicle with Speed {def model: String = moddef tyres: Int = 2def spot { println("\nNew Bike ... ") }override def showModel { println("Unser SuperBIKE: " + model) }
}
class Truck(mod: String, tyr: Int) extends Vehicle with Speed with Fuel{def model: String = moddef tyres: Int = tyrdef spot { println("\nNew Truck ... ") }
}
I As a syntactic shorthand, you can extend a trait directly if you donot care to extend a more specific class. The superclass will betaken to be the same as the traits superclass.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
Using traitsI val scania = new Truck("Brummi", 4)
// Extended Vehicle:scania.spotscania.showModelscania.showTyres
// with Fuel:scania.fuelUp(300)scania.showFuel
// with Speed:scania.speedUp(7)scania.speedUp(14)scania.speedDown(12)scania.showSpeed
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
Thin versus rich interfaces
I One major use of traits is to automatically add methods to a classin terms of methods that the class already has.
I That is, traits can enrich a thin interface, making it into a richinterface.
I A rich interface has many methods, which make it convenient forthe caller.
I A thin interface, on the other hand, has fewer methods, and thusis easier on the implementers.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
Thin versus rich interfaces
I To enrich an interface using traits, simply define a trait with asmall number of abstract methods - the thin part of the trait’sinterface - and a potentially large number of concrete methods,all implemented in terms of the abstract methods.
I Then you can take any class implementing the thin version of theinterface, mix in the enrichment trait, and end up with a classthat has all of the thick interface available.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
Why not multiple inheritance?
I Traits are a way to inherit from multiple class-like constructs, butthey differ in important ways from the multiple inheritancepresent in many languages.
I One difference is especially important: the interpretation of superI With multiple inheritance, the method called by a super call can
be determined right where the call appears.I With traits, the method called is determined by a linearization of
the classes and traits that are mixed into a class.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
Simple code reuse with traits instead of multiple inheritance
Traits
To trait, or not to traitWhenever you implement a reusable collection of behavior, you willhave to decide whether you want to use a trait or an abstract class.There is no firm rule, but here are a few guidelines to consider.
I If the behavior will not be reused, then make it a concrete class.It is not reusable behavior after all.
I If it might be reused in multiple, unrelated classes, then make it atrait. Only traits can be mixed into different parts of the classhierarchy.
I If you want to inherit it in Java code, then use an abstract class.I Inheriting from a Scala class, meanwhile, is exactly like
inheriting from a Java class.I As one exception, a Scala trait with only abstract members
translates directly to a Java interfaceHeiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
A factory object with privat subclasses and traits
Defining a factory object
Basic Information
I A factory object contains methods that construct other objects.I Clients would then use these factory methods for object
construction rather than constructing the objects directly withnew .
I An advantage of this approach is that object creation can becentralized and the details of how objects are represented withclasses can be hidden.
I A straightforward solution is to create a companion object ofclass Element and make this be the factory object for layoutelements.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
A factory object with privat subclasses and traits
Defining a factory object
Private Subclasses
I In Scala, you can define classes and singleton objects insideother classes and singleton objects.
I One way to make the Element subclasses private, therefore, is toplace them inside the Element singleton object and declare themprivate there.
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
A factory object with privat subclasses and traits
Defining a factory object
abstract class Vehicle extends Speed with Fuel {def model: Stringdef tyres: Intdef spotdef showModel { println("Model: " + model) }def showTyres { println("Reifen: " + tyres) }
}object Vehicle {
private class Bike extends Vehicle {def model: String = "Standard-Bike"def tyres: Int = 2def spot { println("\nNew Bike ... ") }override def showModel { println("Unser SuperBIKE: " + model) }
}private class Car(mod: String) extends Vehicle {
def model: String = moddef tyres: Int = 4def spot { println("\nNew Car ... ") }
}private class Truck(mod: String, tyr: Int) extends Vehicle {
def model: String = moddef tyres: Int = tyrdef spot { println("\nNew Truck ... ") }
}def veh: Vehicle = new Bike //def veh(mod: String): Vehicle = new Car(mod) // autom. Auswahldef veh(mod: String, tyr: Int): Vehicle = new Truck(mod, tyr) //
}Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
A factory object with privat subclasses and traits
Defining a factory object
object Main {def main(args: Array[String]): Unit = {
val veh01 = Vehicle.vehveh01.spotveh01.showModelveh01.showTyres
val veh02 = Vehicle.veh("Auto")veh02.spotveh02.showModelveh02.showTyres
val veh03 = Vehicle.veh("Brummi", 16)veh03.spotveh03.showModelveh03.showTyres
}}
New Bike ...Unser SuperBIKE: Standard-BikeReifen: 2
New Car ...Model: AutoReifen: 4
New Truck ...Model: BrummiReifen: 16
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala
Classes & Objects Composition & Inheritance Class Hierarchy Traits Factory Object
A factory object with privat subclasses and traits
Vielen Dank furs Zuhoren ...
Heiko Bremer Universitat Bielefeld
Object Oriented Programming in Scala