visibility modifiers private protected public private protected public
( בהורשה visibility modifiers) כללי הרשאות זו שגיאת , שיטות לא יכולות להידרס ע"י שיטה מרמת שיתוף נמוכה יותר : כלומר. קומפילציה private או protected עם public – לא ניתן לדרוס שיטה private עם שיטה protected – לא ניתן לדרוס שיטה public class Book { public String get. Name() { … } } • public class Dictionary extends Book { protected String get. Name() { … } } Compilation Error Book b = new Dictionary(); System. out. println (b. get. Name() ); ? מה ההיגיון מאחורי שגיאה זו : שאלה 4
public class Business { protected Employee[] employees; protected double monthly. Rent; . . . // calculates total monthly expenses public double monthly. Expenses() { double salaries = calc. Sum(); return this. monthly. Rent + salaries; קריאה לשיטה פרטית } // calculates monthly salaries private double calc. Sum() { double sum = 0; for (int i=0; i<this. employees. length; i=i+1) { sum = sum + this. employees[i]. get. Salary(); } return sum; }. . . } 6
public class Shop extends Business { protected Item[] items; . . . // override: calculates total monthly expenses public double monthly. Expenses() { double item. Prices = calc. Sum(); קריאה לשיטה פרטית return item. Prices + super. monthly. Expenses(); } // No override: calculates total item prices private double calc. Sum() { double sum=0; for (int i=0; i<this. items. length; i=i+1) { sum = sum + this. items[i]. get. Price(); } return sum; }. . . } protected - ל calc. Sum אם נשנה את המאפיין של : שאלה ? monthly. Expenses מה תחשב 7
public class A { public class B extends A { private int x; public int y; public A(int x) { public B(int x. A, int x. B) { this. x = x; super(x. A); this. y = 2*x; this. x = x. B; } this. y = x. A + x. B; public int get. X() { return x; } } public int double. X() { return 2 * get. X(); } public int get. X() { return x; } public int triple. X() { return 3 * x; } public int super. X() { private int sub. Xhelper() { return x - 1; } return super. get. X(); public int sub. X() { } return sub. Xhelper(); public int ten. Times. X() { return 10*x; } } private int sub. Xhelper() { return x-2; } } } A a = new A (1); A b = new B (2, 22); Output / Notes System. out. println(a. get. X()); System. out. println(b. super. X()); 1 22 Compilation Error !! if (b instanceof B) System. out. println(b. super. X()); Compilation Error !! 10
public class A { public class B extends A { private int x; public int y; public A(int x) { public B(int x. A, int x. B) { this. x = x; super(x. A); this. y = 2*x; this. x = x. B; } this. y = x. A + x. B; public int get. X() { return x; } } public int double. X() { return 2 * get. X(); } public int get. X() { return x; } public int triple. X() { return 3 * x; } public int super. X() { private int sub. Xhelper() { return x - 1; } return super. get. X(); public int sub. X() { } return sub. Xhelper(); public int ten. Times. X() { return 10*x; } } private int sub. Xhelper() { return x-2; } } } A a = new A (1); A b = new B (2, 22); Output / Notes B bb = (B)b; System. out. println(bb. super. X()); 2 System. out. println(((B)b). super. X()); System. out. println(a. triple. X()); System. out. println(b. triple. X()); 2 3 6 11
public class A { public class B extends A { private int x; public int y; public A(int x) { public B(int x. A, int x. B) { this. x = x; super(x. A); this. y = 2*x; this. x = x. B; } this. y = x. A + x. B; public int get. X() { return x; } } public int double. X() { return 2 * get. X(); } public int get. X() { return x; } public int triple. X() { return 3 * x; } public int super. X() { private int sub. Xhelper() { return x - 1; } return super. get. X(); public int sub. X() { } return sub. Xhelper(); public int ten. Times. X() { return 10*x; } } private int sub. Xhelper() { return x-2; } } } A a = new A (1); A b = new B (2, 22); Output / Notes System. out. println(((B)a). ten. Times. X()); Run-time Error: Class. Cast. Exception: A cannot be cast to B System. out. println(((B)b). ten. Times. X()); 220 System. out. println(b. double. X()); 44 System. out. println(b. sub. X()); 1 12
public class A { public class B extends A { private int x; public int y; public A(int x) { public B(int x. A, int x. B) { this. x = x; super(x. A); this. y = 2*x; this. x = x. B; } this. y = x. A + x. B; public int get. X() { return x; } } public int double. X() { return 2 * get. X(); } public int get. X() { return x; } public int triple. X() { return 3 * x; } public int super. X() { private int sub. Xhelper() { return x - 1; } return super. get. X(); public int sub. X() { } return sub. Xhelper(); public int ten. Times. X() { return 10*x; } } private int sub. Xhelper() { return x-2; } } } 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); Output / Notes 2 4 24 24 4 13
Throw Runtime. Exception public class Car { private final int MAX_SPEED = 210; private final int MIN_SPEED = -20; private int speed; … public void set. Speed(int speed){ if ((speed >= MIN_SPEED) && (speed <= MAX_SPEED)) this. speed = speed; else throw new Runtime. Exception(“Illegal speed”); } } public static void main(String[] args) { Car car = new Car(); car. set. Speed(300); } Output: Exception in thread "main" java. lang. Runtime. Exception: Illegal Speed at Car. set. Speed(Car. java: 11) at Car. main(Car. java: 17) 16
Exceptions סוגי Object Exception IOException Runtime. Exception Null. Pointer. Exception 17
Throw and Catch Exceptions public class Car { private final int MAX_SPEED = 210; private final int MIN_SPEED = -20; private int speed; … public void set. Speed(int speed) throws Exception { if ((speed >= MIN_SPEED) && (speed <= MAX_SPEED)) this. speed = speed; else throw new Exception(“Illegal speed”); } } public static void main(String[] args) { Car car = new Car(); car. set. Speed(100); } Compilation Error 19
Throw and Catch Exceptions public class Car { private final int MAX_SPEED = 210; private final int MIN_SPEED = -20; private int speed; … public void set. Speed(int speed) throws Exception { if ((speed >= MIN_SPEED) && (speed <= MAX_SPEED)) this. speed = speed; else throw new Exception(“Illegal speed”); } } public static void main(String[] args) { Car car = new Car(); try{ car. set. Speed(300); System. out. println("Broke the speed limit !"); } catch(Exception e){ System. err. println("Caught Exception: "+e. get. Message()); } System. out. println("Current speed is "+car. get. Speed()+” km/h); } Output: Caught Exception: Illegal Speed 20 Current speed is 0 km/h
Spy Robot public abstract class Spy. Robot { private String model; public Spy. Robot(String model) { this. model=model; } public String get. Model() { return this. model; } public abstract void move. Forward(); move. Backward(); turn. Left(); turn. Right(); public void take. Picture() {. . . } public void charge. Battery() {. . . } } 26
Roboquad – Spy Robot public class Legs. Spy. Robot extends Spy. Robot { public Legs. Spy. Robot() { super("Roboquad"); } public void move. Forward() { for(int i=0; i<4; i++) this. move. Leg(i, 1); } public void move. Backward() { for(int i=0; i<4; i++) this. move. Leg(i, -1); } 3 2 public void turn. Right() { public void turn. Left() { this. move. Leg(0, 1); this. move. Leg(0, -1); this. move. Leg(1, -1); this. move. Leg(2, 1); this. move. Leg(3, -1); this. move. Leg(3, 1); } } // direction {1=forward, -1=backward} private void move. Leg(int leg. Id, int dir) {. . . }; } 1 0 27
Spyke – Spy Robot public class Wheels. Spy. Robot extends Spy. Robot { public Wheels. Spy. Robot() { super("Spyke"); } public void move. Forward() { this. turn. Wheels(1, 1); } public void move. Backward() { this. turn. Wheels(-1, -1); } public void turn. Left() { this. turn. Wheels(0, -1); } public void turn. Right() { this. turn. Wheels(-1, 0); } // direction {1=forward, 0=stop, -1=backward} private void turn. Wheels(int right. Dir, int left. Dir) {. . . }; // move features public void wave. Hands() {. . . } } 28
מימוש המחלקה של פעולה כללית public class Action { private String name; public Action(String name) { this. name = name; } public String get. Name(){ return this. name; } public boolean equals(Object other) { boolean ans = false; if(other instanceof Action) ans = this. name. equals(((Action)other). name); return ans; } } 35
מימוש המחלקה של שחקן כללי public abstract class Player { private String name; private int score; public Player(String name){ this. name = name; this. score = 0; } public abstract Action select. Action(Action[] actions); public boolean is. Winner(Player p){ return (this. score > p. get. Score()); } public void update. Score(int score){ this. score = this. score + score; } public int get. Score(){ return this. score; } } 36
מימוש שחקן אקראי public class Random. Player extends Player{ public Random. Player(String name) { super(name); } public Action select. Action(Action[] actions){ int rand. Idx = (int)(Math. random()*actions. length); return actions[rand. Idx]; } } 37
מימוש שחקן עיקבי public class Consecutive. Player extends Player { private int last. Idx; public Consecutive. Player(String name) { super(name); this. last. Idx = 0; } public Action select. Action(Action[] actions) { this. last. Idx = (this. last. Idx + 1) % actions. length; return actions[this. last. Idx]; } } 38
מימוש משחק כללי public abstract class Game { private Player p 1, p 2; private String name; //game name protected Action[] actions; // the set of actions public Game(Player p 1, Player p 2, String name){ this. p 1 = p 1; this. p 2 = p 2; this. name = name; this. init. Actions(); } // There is no real list of actions in a general game protected abstract void init. Actions(); … 39
( כללי )המשך מימוש משחק public abstract class Game { … public void play(int turn. Count) { for (int i=0; i<turn. Count; i=i+1) this. play. Single. Turn(); } private void play. Single. Turn() { /* the selection order is not important * as each player does not * know the choice of the other player */ Action a 1 = this. p 1. select. Action(actions); Action a 2 = this. p 2. select. Action(actions); this. reward. Players(a 1, a 2); } // There is no real scoring strategy in a general game protected abstract void reward. Players(Action a 1, Action a 2); … 40
( כללי )המשך מימוש משחק public abstract class Game { … public Player get. Winner () { if (this. p 1. is. Winner(this. p 2)) return this. p 1; else return this. p 2; } protected Player get. First. Player() { return this. p 1; } protected Player get. Second. Player() { return this. p 2; } } 41
מימוש המשחק אבן נייר ומספריים public class Rock. Paper. Scissors extends Game{ public Rock. Paper. Scissors(Player p 1, Player p 2) { super(p 1, p 2, "Rock Paper Scissors"); } protected void init. Actions(){ this. actions = new Action[3]; this. actions[0] = new Action("rock"); this. actions[1] = new Action("paper"); this. actions[2] = new Action("scissors"); }. . . 42
protected void reward. Players(Action a 1, Action a 2) { int p 1 score = 0; if (!(a 1. equals(a 2))) {// Different actions if ((a 1. get. Name(). equals("rock") && a 2. get. Name(). equals("scissors")) || (a 1. get. Name(). equals("paper") && a 2. get. Name(). equals("rock")) || (a 1. get. Name(). equals("scissors") && a 2. get. Name(). equals("paper"))) { p 1 score = 1; } else { p 1 score = -1; } } this. get. First. Player(). update. Score(p 1 score); this. get. Second. Player(). update. Score(-p 1 score); } } 43
מימוש המשחק דילמת האסיר public class Prisoner. Dilemmas extends Game{ public Prisoner. Dilemmas(Player p 1, Player p 2) { super(p 1, p 2, "Prisoner's Dilemma"); } protected void init. Actions(){ this. actions = new Action[2]; this. actions[0] = new Action("silent"); this. actions[1] = new Action("blame"); }. . . 44
protected void reward. Players(Action a 1, Action a 2) { if (a 1. equals(a 2)) { // Same actions if (a 1. get. Name(). equals("blame") { // blame & blame this. get. First. Player(). update. Score(-5); this. get. Second. Player(). update. Score(-5); } else { // silent & silent this. get. First. Player(). update. Score(-1); this. get. Second. Player(). update. Score(-1); } } else { // Different actions if (a 1. get. Name(). equals("blame") { // blame & silent this. get. First. Player(). update. Score(0); this. get. Second. Player(). update. Score(-15); } else { // silent & blame this. get. First. Player(). update. Score(-15); this. get. Second. Player(). update. Score(0); } } 45
- Slides: 45