11Defining Classes in Java
22========================
33
4- You have already seen how to define classes in Java. Its unavoidable for
4+ You have already seen how to define classes in Java. It's unavoidable for
55even the simplest of programs. In this section we will look at how we
66define classes to create our own data types. Lets start by creating a
77fraction class to extend the set of numeric data types provided by our
@@ -25,20 +25,84 @@ language. The requirements for this new data type are as follows:
2525Here is a mostly complete implementation of a Fraction class in Python
2626that we will refer to throughout this section:
2727
28- .. literalinclude :: fraction.py
28+ .. activecode :: fraction
2929 :language: python
30- :linenos:
3130
31+ class Fraction:
32+ def __init__(self, num, den):
33+ """
34+ :param num: The top of the fraction
35+ :param den: The bottom of the fraction
36+ """
37+ self.num = num
38+ self.den = den
39+
40+ def __repr__(self):
41+ if self.num > self.den:
42+ retWhole = int(self.num / self.den)
43+ retNum = self.num - (retWhole * self.den)
44+ return str(retWhole) + " " + str(retNum) + "/" + str(self.den)
45+ else:
46+ return str(self.num) + "/" + str(self.den)
47+
48+ def show(self):
49+ print(self.num, "/", self.den)
50+
51+ def __add__(self, other):
52+ # convert to a fraction
53+ other = self.toFract(other)
54+ newnum = self.num * other.den + self.den * other.num
55+ newden = self.den * other.den
56+ common = gcd(newnum, newden)
57+ return Fraction(int(newnum / common), int(newden / common))
58+
59+ __radd__ = __add__
60+
61+ def __lt__(self, other):
62+ num1 = self.num * other.den
63+ num2 = self.den * other.num
64+ return num1 < num2
65+
66+ def toFract(self, n):
67+ if isinstance(n, int):
68+ other = Fraction(n, 1)
69+ elif isinstance(n, float):
70+ wholePart = int(n)
71+ fracPart = n - wholePart
72+ # convert to 100ths???
73+ fracNum = int(fracPart * 100)
74+ newNum = wholePart * 100 + fracNum
75+ other = Fraction(newNum, 100)
76+ elif isinstance(n, Fraction):
77+ other = n
78+ else:
79+ print("Error: cannot add a fraction to a ", type(n))
80+ return None
81+ return other
82+
83+
84+ def gcd(m, n):
85+ """
86+ A helper function for Fraction
87+ """
88+ while m % n != 0:
89+ oldm = m
90+ oldn = n
91+ m = oldn
92+ n = oldm % oldn
93+ return n
94+
95+ print(sorted([Fraction(5, 16), Fraction(3, 16), Fraction(1, 16) + 1]))
3296
3397The instance variables (data members) we will need for our fraction
3498class are the numerator and denominator. Of course in Python we can add
3599instance variables to a class at any time by simply assigning a value to
36- ``objectReferenc .variableName `` In Java all data members must be
100+ ``objectReference .variableName ``, whereas in Java all data members must be
37101declared up front.
38102
39103The declarations of instance variables can come at the beginning of the
40- class definition or the end. Cay Horstman, Author of the * Core Java *
41- books puts the declarations at the end of the class. I like them at the
104+ class definition or the end. Cay Horstman, author of ` the " Core Java"
105+ books <https://horstmann.com/corejava/index.html> `_ puts the declarations at the end of the class. I like them at the
42106very beginning so you see the variables that are declared before you
43107begin looking at the code that uses them. With that in mind the first
44108part of the Fraction class definition is as follows:
@@ -52,8 +116,6 @@ part of the Fraction class definition is as follows:
52116 public class Fraction {
53117 private Integer numerator;
54118 private Integer denominator;
55-
56-
57119 }
58120
59121Notice that we have declared the numerator and denominator to be
0 commit comments