|
1 package greeter |
|
2 |
|
3 object Chapter6 { |
|
4 println("Classes and Objects") //> Classes and Objects |
|
5 |
|
6 class Rational(n: Int, d: Int) { |
|
7 private def gcd(x: Int, y: Int): Int = { |
|
8 if (x == 0) y |
|
9 else if (x < 0) gcd(-x, y) |
|
10 else if (y < 0) -gcd(x, -y) |
|
11 else gcd(y % x, x) |
|
12 } |
|
13 private val g = gcd(n, d) |
|
14 |
|
15 val numer: Int = n / g |
|
16 val denom: Int = d / g |
|
17 def +(that: Rational) = new Rational(numer * that.denom + that.numer * denom, denom * that.denom) |
|
18 def -(that: Rational) = new Rational(numer * that.denom - that.numer * denom, denom * that.denom) |
|
19 def *(that: Rational) = new Rational(numer * that.numer, denom * that.denom) |
|
20 def /(that: Rational) = new Rational(numer * that.denom, denom * that.numer) |
|
21 |
|
22 //Inheritance and Overriding |
|
23 override def toString = "" + numer + "/" + denom |
|
24 //Parameterless Methods |
|
25 def square = new Rational(numer * numer, denom * denom) |
|
26 } |
|
27 //Inheritance and Overriding |
|
28 var i = 1 //> i : Int = 1 |
|
29 var x = new Rational(0, 1) //> x : greeter.Chapter6.Rational = 0/1 |
|
30 while (i <= 10) { |
|
31 x += new Rational(1, i) |
|
32 i += 1 |
|
33 } |
|
34 println("" + x.numer + "/" + x.denom) //> 7381/2520 |
|
35 //Parameterless Methods |
|
36 val r = new Rational(3, 4) //> r : greeter.Chapter6.Rational = 3/4 |
|
37 println(r.square) //> 9/16 |
|
38 |
|
39 //Abstract Classes |
|
40 abstract class IntSet { |
|
41 def incl(x: Int): IntSet |
|
42 def contains(x: Int): Boolean |
|
43 } |
|
44 |
|
45 //Triats |
|
46 trait IntSett { |
|
47 def incl(x: Int): IntSet |
|
48 def contains(x: Int): Boolean |
|
49 } |
|
50 |
|
51 //Implementing abstract class |
|
52 class EmptySet extends IntSet { |
|
53 def contains(x: Int): Boolean = false |
|
54 def incl(x: Int): IntSet = new NonEmptySet(x, new EmptySet, new EmptySet) |
|
55 } |
|
56 |
|
57 class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet { |
|
58 def contains(x: Int): Boolean = |
|
59 if (x < elem) left contains x |
|
60 else if (x > elem) right contains x |
|
61 else true |
|
62 def incl(x: Int): IntSet = |
|
63 if (x < elem) new NonEmptySet(elem, left incl x, right) |
|
64 else if (x > elem) new NonEmptySet(elem, left, right incl x) |
|
65 else this |
|
66 } |
|
67 |
|
68 } |