תרגול 10 המשך תכנות מונחה עצמים 1
היום בתרגול פולימורפיזם כללי הרשאות בהורשה מחלקות אבסטרקטיות 2
פולימורפיזם (רב צורתיות) התייחסות לעצמים שונים (instance) כדברים דומים (reference) בעלי מכנה משותף. אם נרצה למשל להחזיק מערך של ספרים, אשר יוכל להחזיק ספרים מסוגים שונים, נוכל להגדיר מערך של מצביעים (reference) מטיפוס Book. משתנה (מצביע) מטיפוס מסוים יכול להצביע על כל אובייקט שטיפוסו הוא צאצא של טיפוס זה. לכן, מערך של מצביעים מטיפוס Book יוכל להצביע על אובייקטים מטיפוסים שיורשים את Book. 3
4 Book DictionaryCookbook public class Book { private String m_name; private int m_pages; public Book(String name, int p){ this. m_name = new String(name); this. m_pages = p; } public String getName(){ return this. m_name; } public void message() { System.out.println(this. m_name +": " + this. m_pages + " pages"); }
5 Book DictionaryCookbook /* A Dictionary is a kind of Book with definitions */ public class Dictionary extends Book { private int m_definitions; public Dictionary(String name, int pages, int defs) { super(name, pages); this. m_definitions = defs; } public void message() { System.out.println(getName() + ": " + m_definitions + " definitions"); } public int getDefinitions(){ return this. m_definitions; }
6 Book DictionaryCookbook /* A Cook Book is a kind of Book with recipes */ public class Cookbook extends Book { private int m_recipes; public Cookbook(String name, int pages, int recipes) { super(name, pages); this. m_recipes = recipes ; } public void message() { System.out.println(getName() + ": " + this. m_recipes + " recipes "); }
שימוש בפולימורפיזם התייחסות לספרים שונים באופן אחיד לפי יכולות מחלקת האב: books Output Webster: definitions Naked Chef: 50 recipes War and Peace: 1000 pages 7 public static void main(String[] args) { Book [] books = new Book[3]; // new above is for the array not Book objects books[0] = new Dictionary("Webster“, 690, 45056); books[1] = new Cookbook("Naked Chef“, 100, 50); books[2] = new Book("War and Peace“, 1000); for (int i=0; i<books.length; i=i+1) books[i].message(); }
שימוש בפולימורפיזם התייחסות לספרים שונים באופן אחיד לפי יכולות מחלקת האב: public static void main(String[] args) { Book [] books = new Book[3]; // new above is for the array not Book objects books[0] = new Dictionary("Webster“, 690, 45056); books[1] = new Cookbook("Naked Chef“, 100, 50); books[2] = new Book("War and Peace“, 1000); books[0].getDefinitions(); // what would this line do ? } books // compilation error - no getDefinitions() for Book בעזרת Casting שימו לב: תכנון נכון של המחלקות יכלול דריסת פונקציות במקום Casting איך ניתן בכל זאת להפעיל שיטה ספציפית? 8 ((Dictionary)books[0]).getDefinitions();
פולימורפיזם הינו "חד-כיווני" משתנה מטיפוס Cookbook לא יכול להכיל אובייקט מטיפוס Book. (כי טיפוס מחלקת האב הוא כללי יותר) השורה: Cookbook deserts = new Book() תיתן שגיאת קומפילציה 9 Book DictionaryCookbook
כללי הרשאות (visibility modifiers) בהורשה public – שדות ושיטות המוגדרים כ-public ניתנים לגישה מתוך ומחוץ למחלקה. protected – שדות ושיטות המוגדרים כ-protected ניתן לגישה מתוך המחלקה וממחלקות היורשות מהמחלקה אך אינם ניתן לגישה ממחלקות אחרות *. (* ממחלקות אחרות הנמצאות ב package אחר. protected מתנהג כמו public באותו package) private – שדות ושיטות המוגדרים כ-private אינם ניתנים לגישה מחוץ למחלקה. ניסיון לגשת לשדה או שיטה כזו מחוץ למחלקה יעורר שגיאת קומפילציה. 10
שיטות לא יכולות להידרס ע"י שיטה מרמת שיתוף נמוכה יותר, זו שגיאת קומפילציה. כלומר: –לא ניתן לדרוס שיטה public עם protected או private –לא ניתן לדרוס שיטה protected עם שיטה private class Book { public String getName() { … } class Dictionary extends Book { protected String getName() { … } Compilation Error שאלה: מה ההיגיון מאחורי שגיאה זו? 11 Book b = new Dictionary(); S.O.P(b.getName()); כללי הרשאות (visibility modifiers) בהורשה
משתנים אינם עוברים דריסה בהורשה. שיטות שאינן private עוברות בהורשה. –נועדו למימוש פנימי של מחלקת האב, ואינם ניתנים לשימוש ע"י תת מחלקה. –תת-המחלקה לא מכירה את המשתנים והשיטות הפרטיות של המחלקת האב, ממנה היא יורשת, ולכן עשויה גם להכריז על משתנים ושיטות פרטיות בעלי אותו שם וחתימה. דוגמה: –חנות היא סוג של עסק עסק: דמי שכירות, עובדים, הוצאות חודשיות חנות: פריטי סחורה, הוצאות חודשיות הכוללות אחזקת מלאי. –כל אחד מהם מומש ע"י מתכנת אחר –בכל אחד מימוש שונה לשיטה פרטית - calcSum() 12 כללי הרשאות (visibility modifiers) בהורשה
public class Business { protected Employee[] m_ employees; protected double m_ monthlyRent; // calculates total monthly expenses public double monthlyExpenses() { double salaries = calcSum(); return this. m_ monthlyRent + salaries; } // calculates monthly salaries private double calcSum() { double sum = 0; for (int i=0; i<this. m_ employees.length; i=i+1) sum = sum + this. m_ employees[i].getSalary(); return sum; } } 13 קריאה לשיטה פרטית
public class Shop extends Business { protected Item[] m_items; // override: calculates total monthly expenses public double monthlyExpenses() { double itemPrices = calcSum(); return itemPrices + super.monthlyExpenses(); } // No override: calculates total item prices private double calcSum() { double sum=0; for (int i=0; i<this. m_items.length; i=i+1){ sum = sum + this. m_items[i].getPrice(); } return sum; } } 14 שאלה: אם נשנה את המאפיין של calcSum ל-protected מה תחשב monthlyExpenses? קריאה לשיטה פרטית
סיכום חוקי גישה לשיטות ושדות בהורשה ב Java: 1.טיפוס המשתנה (טיפוס המצביע/ reference type) קובע בזמן הידור אילו שיטות ניתן להפעיל על המשתנה ולאילו שדות של המשתנה ניתן לגשת. 2.בקריאה לשיטה שאינה פרטית המופיעה במחלקת-אב ובתת-מחלקה, אם ע"י קריאה ישירה או ע"י שימוש באופרטור השייכות (.), הקוד המופעל נקבע בהתאם למחלקת האובייקט בפועלinstance type) ) שעליו מופעלת השיטה (ומשם בסריקה מלמטה למעלה לפי היררכית ההורשה). 3.שיטה פרטית נגישה רק בתוך ה- scope של המחלקה בה היא מוגדרת. בקריאה לשיטה פרטית, הקוד המופעל נקבע לפי ה -scope בו ממוקמת הקריאה. 4.בגישה לשדה (קריאה או השמה), ע"י גישה ישירה (ללא אופרטור השייכות), הגישה לשדה נקבעת לפי ה-scope בה ממוקמת הגישה (ומשם בסריקה מלמטה למעלה לפי היררכית ההורשה). 5.בגישה לשדה (קריאה או השמה) שאינו פרטי, ע"י אופרטור השייכות, בהתאם למחלקת טיפוס המשתנהreference type) ) שעליו מופעלת השיטה (ושם בסריקה מלמטה למעלה לפי היררכית ההורשה). 15
דוגמה להורשה (שאלה ממבחן) 16
A a = new A (1); A b = new B (2, 22); System.out.println(a.getX()); System.out.println(b.getX()); System.out.println(b.superX()); 1 22 Compilation Error !! Output / Notes if (b instanceof B) System.out.println(b.superX()); Compilation Error !! 17 public class A { private int x; public int y; public A(int x){ this.x = x; this.y = 2*x; } public int getX() { return x; } public int doubleX() { return 2 * getX(); } public int tripleX() { return 3 * x; } private int subXhelper() { return x - 1; } public int subX() { return subXhelper(); } public class B extends A { private int x; public int y; public B(int xA, int xB) { super(xA); this.x = xB; this.y = xA + xB; } public int getX() { return x; } public int superX() { return super.getX(); } public int tenTimesX() { return 10*x; } private int subXhelper() { return x-2; } }
A a = new A (1); A b = new B (2, 22); Output / Notes 18 public class A { private int x; public int y; public A(int x){ this.x = x; this.y = 2*x; } public int getX() { return x; } public int doubleX() { return 2 * getX(); } public int tripleX() { return 3 * x; } private int subXhelper() { return x - 1; } public int subX() { return subXhelper(); } public class B extends A { private int x; public int y; public B(int xA, int xB) { super(xA); this.x = xB; this.y = xA + xB; } public int getX() { return x; } public int superX() { return super.getX(); } public int tenTimesX() { return 10*x; } private int subXhelper() { return x-2; } } B bb = (B)b; System.out.println(bb.superX()); 2 System.out.println(((B)b).superX()); 2 System.out.println(a.tripleX()); System.out.println(b.tripleX()); 3 6
System.out.println(b.subX()); System.out.println(((B)b).tenTimesX()); System.out.println(b.doubleX()); public class A { private int x; public int y; public A(int x){ this.x = x; this.y = 2*x; } public int getX() { return x; } public int doubleX() { return 2 * getX(); } public int tripleX() { return 3 * x; } private int subXhelper() { return x - 1; } public int subX() { return subXhelper(); } public class B extends A { private int x; public int y; public B(int xA, int xB) { super(xA); this.x = xB; this.y = xA + xB; } public int getX() { return x; } public int superX() { return super.getX(); } public int tenTimesX() { return 10*x; } private int subXhelper() { return x-2; } } System.out.println(((B)a).tenTimesX()); Run-time Error: ClassCastException: A cannot be cast to B Output / Notes A a = new A (1); A b = new B (2, 22);
20 public class A { private int x; public int y; public A(int x){ this.x = x; this.y = 2*x; } public int getX() { return x; } public int doubleX() { return 2 * getX(); } public int tripleX() { return 3 * x; } private int subXhelper() { return x - 1; } public int subX() { return subXhelper(); } public class B extends A { private int x; public int y; public B(int xA, int xB) { super(xA); this.x = xB; this.y = xA + xB; } public int getX() { return x; } public int superX() { return super.getX(); } public int tenTimesX() { return 10*x; } private int subXhelper() { return x-2; } } Output / Notes A a = new A (1); A b = new B (2, 22); System.out.println(a.y); System.out.println(b.y); System.out.println(((B)b).y); B bb= (B)b; System.out.println(bb.y); System.out.println(((A)bb).y);
מחלקות אבסטרקטיות כאשר רוצים לחלוק קוד משותף בין מספר מחלקות למרות שאין רצון לאפשר יצירת אובייקטים ממחלקת האב. –מכילה קוד משותף. –קובעת אילו שיטות אבסטרקטית על תתי המחלקות לממש. –תת-מחלקה קונקרטית מממשת שיטות אבסטרקטיות. 21
מחלקות אבסטרקטיות public abstract class { public abstract void (... ); … } במחלקה אבסטרקטית יכולות להיות שיטות רגילות, כמו בכל מחלקה. בנוסף יכולות להיות לה שיטות אבסטרקטיות: שיטות שההגדרה שלהן קיימת אבל אין להן מימוש. אנו מכריזים על מחלקה או על שיטה כאבסטרקטית בעזרת המילה השמורה abstract. 22
מחלקות אבסטרקטיות מחלקה אבסטרקטית -לא ניתן ליצור ממנה מופעים. public abstract class Game { public Game() { … } … } Game g = new Game(); // Compilation error! מחלקה שמרחיבה מחלקה אבסטרקטית ולא מממשת את כל השיטות האבסטרקטיות, חייבת להיות אבסטרקטית בעצמה. 23
Spy Robot (רובוט מעקב) הינו רובוט הנשלט מרחוק ומאפשר צילום תמונות ושלחתם. רובוט מעקב יכול לבצע את הפעולות הבאות: –לצלם תמונות ולשדר אותן –לזוז קדימה / אחרונה –להסתובב ימינה / שמאל 24 Spy Robot
נסתכל על 2 רובוטי מעקב שניהם יכולים לצלם תמונות ולשדר באותה דרך אך הם זזים בדרכים שונות. 25 Spy Robot
26 Spy Robot public abstract class SpyRobot { private String m_model; public SpyRobot(String model) { this. m_model=model; } public String getModel() { return this. m_model; } public abstract void moveForward(); public abstract void moveBackward(); public abstract void turnLeft(); public abstract void turnRight(); public void takePicture() {... } public void chargeBattery() {... } }
27 Roboquad – Spy Robot public class LegsSpyRobot extends SpyRobot { public LegsSpyRobot() { super("Roboquad"); } public void moveForward() { for(int i=0; i<4; i++) this.moveLeg(i, 1); } public void moveBackward() { for(int i=0; i<4; i++) this.moveLeg(i, -1); } public void turnLeft() { this.moveLeg(0,-1); this.moveLeg(1,-1); this.moveLeg(2,1); this.moveLeg(3,1); } // direction {1=forward, -1=backward} private void moveLeg(int legId, int dir) {... }; } public void turnRight() { this.moveLeg(0,1); this.moveLeg(1,1); this.moveLeg(2,-1); this.moveLeg(3,-1); }
28 Spyke – Spy Robot public class WheelsSpyRobot extends SpyRobot { public WheelsSpyRobot() { super("Spyke"); } public void moveForward() { this. turnWheels(1,1); } public void moveBackward() { this. turnWheels(-1,-1); } public void turnLeft() { this. turnWheels(0,-1); } public void turnRight() { this. turnWheels(-1,0); } // direction {1=forward, 0=stop, -1=backward} private void turnWheels(int rightDir,int leftDir) {... }; // move features public void waveHands() {... } }
29 Fly – Spy Robot את זה אתם כבר יכולים לממש לבד ?
נממש משחקים מתורת המשחקים ע"י הורשה: –משחק מוגדר על ידי מערכת של פעולות אפשריות ושיטת ניקוד. –במשחק משחקים שני שחקנים כאשר שני השחקנים בוחרים פעולה בו-זמנית. –בהינתן שתי הבחירות של השחקנים יקבלו השחקנים ניקוד ע"פ בחירתם. 30 דוגמא נוספת
דוגמה: אבן נייר ומספריים בחירה מבין שלוש הפעולות האפשריות (אבן, נייר או מספריים). –אבן שוברת מספריים. –מספריים גוזרים נייר. –נייר עוטף אבן. 31
דוגמה: דילמת האסיר המשטרה עוצרת שני עבריינים שביצעו פשע משותף, ומפרידה ביניהם לצורך חקירה. המשטרה מציעה לכל אחד מהם להעיד נגד רעהו, וכפרס מובטח לעד עונש מופחת. בחירה מבין הפעולות האפשריות: להעיד או לשתוק. ניקוד: –אם שניהם יעידו, ייכנס כל אחד מהם לכלא לחמש שנים. –אם רק אחד מהם יעיד ורעהו ישתוק, העד יצא מיד לחופשי וחברו ייכלא ל-15 שנה. –אם שניהם ישתקו, יכנס כל אחד מהם לשנה בכלא. 32
המחלקות שעלינו לממש פעולה Action –שם הפעולה ("אבן") שחקן Player –שם השחקן (" Andrea Farina ") –מספר נקודות –בחירת פעולה(מהלך) מתוך קבוצת פעולות אפשריות. משחק Game – קבוצת פעולות אפשריות –שיטת ניקוד – 2 שחקנים – שם המשחק 33
מימוש המחלקה של פעולה כללית public class Action { private String m_name; public Action(String n) { this.m_name = n; } public String getName(){ return this.m_name; } public boolean equals(Object other) { boolean ans = false; if(other instanceof Action) ans = this. m_name.equals(((Action)other). m_name); return ans; } 34
מימוש המחלקה של שחקן כללי public abstract class Player { private String m_name; private int m_score; public Player(String pname){ this. m_name= pname; this. m_score =0; } public abstract Action selectAction(Action[] actions); public boolean isWinner(Player p){ return (this. m_score > p.getScore()); } public void updateScore(int score){ this. m_score = m_score+ score; } public int getScore(){ return this. m_score; } 35
מימוש שחקן אקראי public class RandomPlayer extends Player{ public RandomPlayer(String name) { super(name); } public Action selectAction(Action[] actions){ int randIdx = (int)(Math.random()*actions.length); return actions[randIdx]; } 36
מימוש שחקן עיקבי public class ConsecutivePlayer extends Player { private int m_lastIdx; public ConsecutivePlayer(String name) { super(name); this. m_lastIdx = 0; } public Action selectAction(Action[] actions) { this. m_lastIdx = (this. m_lastIdx + 1) % actions.length; return actions[this. m_lastIdx]; } 37
38 public abstract class Game { private Player p1, p2; private String name; //game name protected Action[] actions; // the set of actions public Game(Player p1, Player p2, String name){ this.p1 = p1; this.p2 = p2; this.name = name; this.initActions(); } // There is no real list of actions in a general game protected abstract void initActions(); … מימוש משחק כללי
public abstract class Game { … public void play(int turnCount) { for (int i=0; i<turnCount; i=i+1) this.playSingleTurn(); } private void playSingleTurn() { /* the selection order is not important * as each player does not * know the choice of the other player */ Action a1 = this.p1.selectAction(actions); Action a2 = this.p2.selectAction(actions); this.rewardPlayers(a1, a2); } // There is no real scoring strategy in a general game protected abstract void rewardPlayers(Action a1, Action a2); … 39 מימוש משחק כללי (המשך)
public abstract class Game { … public Player getWinner () { if (this.p1.isWinner(this.p2)) return this.p1; else return this.p2; } protected Player getFirstPlayer() { return this.p1; } protected Player getSecondPlayer() { return this.p2; } 40 מימוש משחק כללי (המשך)
מימוש המשחק אבן נייר ומספריים public class RockPaperScissors extends Game{ public RockPaperScissors(Player p1, Player p2) { super(p1, p2, "Rock Paper Scissors"); } protected void initActions(){ this.actions = new Action[3]; this.actions[0] = new Action("rock"); this.actions[1] = new Action("paper"); this.actions[2] = new Action("scissors"); }... 41
42 protected void rewardPlayers(Action a1, Action a2) { int p1score = 0; if (!(a1.getName().equals(a2.getName()))) { if ((a1.getName().equals("rock") && a2.getName().equals("scissors")) || (a1.getName().equals("paper") && a2.getName().equals("rock")) || (a1.getName().equals("scissors") && a2.getName().equals("paper"))) { p1score = 1; } else { p1score = -1; } this.getFirstPlayer().updateScore(p1score); this.getSecondPlayer().updateScore(-p1score); }
מימוש המשחק דילמת האסיר public class PrisonerDilemmas extends Game{ public PrisonerDilemmas(Player p1, Player p2) { super(p1, p2, "Prisoner's Dilemma"); } protected void initActions(){ this.actions = new Action[2]; this.actions[0] = new Action("silent"); this.actions[1] = new Action("blame"); }... 43
protected void rewardPlayers(Action a1, Action a2) { if (a1.getName().equals("blame") && a2.getName().equals("blame")) { this.getFirstPlayer().updateScore(-5); this.getSecondPlayer().updateScore(-5); } if (a1.getName().equals("silent") && a2.getName().equals("blame")) { this.getFirstPlayer().updateScore(-15); this.getSecondPlayer().updateScore(0); } if (a1.getName().equals("blame") && a2.getName().equals("silent")) { this.getFirstPlayer().updateScore(0); this.getSecondPlayer().updateScore(-15); } if (a1.getName().equals("silent") && a2.getName().equals("silent")) { this.getFirstPlayer().updateScore(-1); this.getSecondPlayer().updateScore(-1); } 44
מחלקות אבסטרקטיותממשקים לא ניתן ליצור מופעים שימוש ע"י ירושה extendsשימוש ע"י מימושו implements יכולה להכיל קוד של חלק מהשיטותהכרזה של שיטות בלי מימוש יורשי מחלקה זו יהיו בעלי קוד משותף וכן בעלי התנהגויות שונות (השיטות האבסטרקטיות) ממשק הוא הכרזה על תכונה מופשטת, למממשים אין קוד משותף. מחלקה יכולה לרשת מחלקה (אבסטרקטית) אחת בלבד מחלקה יכולה לממש מספר ממשקים אין הגבלה על המשתניםרק קבועים וסטאטיים 45