9 public class Complex public double mreal public
9
בנאי – שיטה מיוחדת עבור מחלקה שתפקידה לייצר אובייקט ולאתחל את שדותיו public class Complex{ public double m_real; public double m_im; השם זהה לשם המחלקה ואין ערך החזרה public Complex(){ m_real = 0; m_im = 0; } } Complex: double m_real; double m_im; Complex() 11
: ניתן להוסיף בנאים אחרים public Complex(double real. Part, double im. Part){ m_real = real. Part; m_im = im. Part; } יצירת אובייקט חדש על בסיס אובייקט - Copy constructor קיים מאותו טיפוס public Complex(Complex other){ m_im = other. m_im; m_real = other. m_real; } '. ' למה לא משתמשים באופרטור ? בגישה לשדות 12
Complex() Complex: to. String() double m_real; double m_im; Complex( double rp, double ip) 15
לפי הגדרת הערך. שיטה המוצאת ערך מוחלט Complex נוסיף למחלקה . המוחלט השיטה תחזיר מספר ממשי public class Complex{ public double m_real; public double m_im; ……… public double abs(){ return Math. sqrt(m_real*m_real + m_im*m_im); } } 18
. שיטה המעדכנת את הערך הממשי והערך המדומה Complex נוסיף למחלקה public class Complex{ public double m_real; public double m_im; ……… public void update(double other_real, double other_im){ m_real = other_real; m_im = other_im; } } 19
חיבור public class Complex{ … public Complex add(Complex other){ Complex result = new Complex(m_real+other. m_real, m_im+other. m_im); return result; } } 21
add השימוש בשיטה . מחזירה אובייקט חדש add השיטה : שימו לב Complex c 1 = new Complex(1, 0. 5); Complex c 2 = new Complex(10. 1, 9); Complex c 3 = c 1. add(c 2); System. out. println(c 3. to. String()); // 11. 1 + 9. 5 i 22
הפתרון public Complex add(Complex other){ Complex result = null; if (other != null) { result = new Complex(m_real + other. m_real, m_im + other. m_im); } return result; } 25
כפל public Complex mult(Complex other){ Complex result = null; if (other != null) { double multreal = m_real * other. m_real – m_im*other. m_im; double multim = m_real*other. m_im + m_im*other. m_real; result = new Complex(multreal, multim); } return result; } 26
27
FIELDS Constructor String to. String() int add. Points(int points) 33
34
36
37
38
39
Java Documentation 40
/** * Class representing a player in a die game */ public class Player{ /** Player name */ public String name; /** Player score */ public int score; /** * Creates a new Player with the name player. Name and a score of 0 * @param player. Name the player name */ public Player(String player. Name){ name = player. Name; score = 0; } /** * Add points to player score * @param points number of points to add * @return new score value */ public int add. Points(int points){ score += points; return score; } } 44 44
כיצד להוציא זאת כפלט בעזרת ? אקליפס http: //www. eclipse-blog. org/eclipse-ide/generating-javadoc-in-eclipse-ide. html 45
- Slides: 45