Professional Documents
Culture Documents
Scala
08, 2016
1 OOP Introduction
2 Scala
Animal
B C
radius
Circle draw()
p.draw()
Dynamic binding
Class
class [1]
abstract class [5]
trait [2]
case class [3]
Object
new <class name>
<case class name>
object
class R a t i o n a l ( n : I n t , d : I n t ) {
r e q u i r e ( d != 0)
def t h i s ( n : I n t ) = t h i s ( n , 1 )
def + ( t h a t : R a t i o n a l ) : R a t i o n a l =
new R a t i o n a l (
numer ∗ t h a t . denom + t h a t . numer ∗ denom ,
denom ∗ t h a t . denom
)
a b s t r a c t class Element {
def c o n t e n t s : A r r a y [ S t r i n g ] / / no body : a b s t r a c t
val height = contents . length
val width =
i f ( h e i g h t == 0 ) 0 else c o n t e n t s ( 0 ) . l e n g t h
}
class ArrayElement ( c o n t s : A r r a y [ S t r i n g ] )
extends Element {
def c o n t e n t s : A r r a y [ S t r i n g ] = c o n t s
}
class LineElement ( s : S t r i n g )
extends ArrayElement ( A r r a y ( s ) ) {
override def w i d t h = s . l e n g t h
override def h e i g h t = 1
}
object Element {
a b s t r a c t class Expr
t r a i t Flying {
def f l y M e s s : S t r i n g
def f l y ( ) = p r i n t l n ( f l y M e s s )
}
t r a i t Swimming {
def swim ( ) = p r i n t l n ( " I ’m swimming " )
}
Stackable Modifications:
a b s t r a c t class IntQueue {
def g e t ( ) : I n t
def p u t ( x : I n t ) }
class BasicIntQueue extends IntQueue {
p r i v a t e v a l b u f = new A r r a y B u f f e r [ I n t ]
def g e t ( ) = b u f . remove ( 0 )
def p u t ( x : I n t ) { b u f += x } }
t r a i t Doubling extends IntQueue {
a b s t r a c t override def p u t ( x : I n t ) { super . p u t ( 2 ∗ x ) } }
t r a i t I n c r e m e n t i n g extends IntQueue {
a b s t r a c t override def p u t ( x : I n t ) { super . p u t ( x + 1 ) } }
v a l queue =
new BasicIntQueue with I n c r e m e n t i n g with Doubling
queue . p u t ( 1 0 )
queue . g e t ( ) / / ? ? ?
public
protected
private
protected[<name>]
private[<name>]
Example,
package Assignment
...
protected [ Assignment ] v a l f i e l d 1 = 100
private [ t h i s ] val f i e l d 2 = 2;