Lesson 3 PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

‫מבוא למדעי המחשב ושפת ‪Java‬‬

‫)‪(20441‬‬
‫מפגש ‪3‬‬

‫‪© Eli Koren‬‬


...‫אז מה היה לנו‬
main -‫עד עכשיו כתבנו תוכניות שמורכבות רק מ‬
‫ אבל לא יצרנו‬,(Scanner) ‫עשינו שימוש במחלקה קיימת‬
‫מחלקה חדשה המייצגת אובייקט‬
import java.util.Scanner;
public class WomanPensionAge {
public static void main() {
// a constant for the pension age of women
final int WOMAN_PENSION_AGE = 64;
int age; // holds the age of the user

Scanner scan = new Scanner(System.in);


// prompt the user to enter her age
System.out.println(“Please enter your age:");
age = scan.nextInt();
}
}
© Eli Koren
‫תכנות מונחה עצמים )‪(OOP‬‬
‫מה זה אובייקט?‬
‫תכונות )‪(Attributes‬‬
‫שיטות )‪(Methods‬‬
‫הודעות )‪(Messages‬‬

‫‪© Eli Koren‬‬


‫תכנות מונחה עצמים )‪(OOP‬‬
‫מה זה אובייקט?‬
‫צורת המחשבה שלנו וחיי היום יום שלנו‬
‫מבוססים על עצמים בעלי תכונות ופעולות‬
‫המתקשרים בניהם בדרכים שונות‬
‫בניית מודל במחשב‪ ,‬המייצג את הבעיה אותה‬
‫אנחנו רוצים לפתור‬
‫מחלקה היא דרך מופשטת לתיאור של כל‬
‫העצמים )אובייקטים( מאותו סוג‬
‫‪© Eli Koren‬‬
‫תכונות עיקריות של ‪OOP‬‬
‫ריכוזיות – ‪) encapsulation‬יחידה ‪(7‬‬

‫ירושה – ‪) inheritance‬יחידה ‪(11‬‬

‫רב צורתיות – ‪) polymorphism‬יחידה ‪(11‬‬

‫‪© Eli Koren‬‬


‫מבנה כללי של מחלקה‬
‫{ ‪class NameOfClass‬‬
‫הצהרות על משתנים וקבועים ‪//‬‬
‫‪declarations‬‬
‫הוראות ליצירת ואתחול האובייקט ‪//‬‬
‫‪constructor definitions‬‬
‫הצהרות והגדרות של המתודות ‪//‬‬
‫‪method definitions‬‬
‫}‬
‫‪© Eli Koren‬‬
‫דוגמא‬
‫כתיבת מחלקה בשם ‪ .PiggyBank‬מחלקה זו‬
‫תייצג קופת חסכון בדולרים‬

‫בשלב ראשון נכתוב שלד למחלקה )ריקה(‬


‫ונשמור בקובץ בשם ‪PiggyBank.java‬‬

‫{ ‪public class PiggyBank‬‬


‫}‬

‫עכשיו נמלא את המחלקה לפי המבנה שלמדנו‬


‫‪© Eli Koren‬‬
(‫דוגמא )המשך‬
public class PiggyBank {

private int _dollars;


private int _cents; declarations

public PiggyBank () { // default constructor


_dollars = 0;
constructor
_cents = 0;
definitions
}
public PiggyBank (int dollars, int cents) {
_dollars = dollars;
_cents = cents;
}
© Eli Koren
public PiggyBank addMoney (int dollars, int cents) {
int newDollars = _dollars + dollars;
int newCents = _cents + cents;
if (newCents > 99) {
newDollars += newCents / 100;
newCents = newCents % 100; method
} definitions
return (new PiggyBank(newDollars, newCents));
}
public void printStatus () {
System.out.println(“You have “ + _dollars +
“ dollars and ” + _cents +
“ cents in your piggy bank!”);
}
} // end of class
© Eli Koren
(‫מבנה של שיטה )מתודה‬
[Access Modifier] [returned value] name (parameters)
{
// method’s body
}
‫ או‬public) ‫ – הרשאת גישה‬Access Modifier
(private
‫ – סוג הערך שהשיטה‬Returned value
(‫ אם לא מחזירה ערך‬void) ‫מחזירה‬
‫ – שם השיטה‬name
‫ – הפרמטרים שצריכים להיות‬parameters
© Eli Koren
‫מועברים לשיטה‬
(‫סוגים של שיטות )מתודות‬
(void) ‫שיטה שלא מחזירה ערך‬
public void print () {
System.out.println(“Void example”);
}
‫שיטה שמחזירה ערך מטיפוס פשוט או אובייקט‬
public int getDollars () {
return (_dollars);
}
int dollars = piggy.getDollars() :‫השימוש‬
© Eli Koren
‫פרמטרים פורמליים‬
‫שיטה יכולה לקבל פרמטרים מטיפוסים שונים )פשוטים או‬
‫אובייקט(‬
‫{ )‪public void executeMission (int code,boolean status‬‬
‫…‬ ‫‪formal parameters‬‬
‫}‬
‫;)‪soldier.executeMission (2, true‬‬ ‫השימוש‪:‬‬
‫‪actual parameters‬‬

‫וסוג הפרמטרים הריאליים‬ ‫חייבת להיות התאמה בין מספר‬


‫והפרמטרים הפורמליים‬

‫‪© Eli Koren‬‬


‫משתנים כלליים ומקומיים‬
public class PiggyBank {
private int _dollars;
private int _cents;
‫משתנים כלליים‬
//constructor…
public PiggyBank addMoney (int dollars, int cents) {
int newDollars = _dollars + dollars;
int newCents = _cents + cents;
‫משתנים מקומיים‬
if (newCents > 99) {
newDollars += newCents / 100;
newCents = newCents % 100;
}
return (new PiggyBank(newDollars, newCents));
}
}
© Eli Koren
‫קווים מנחים בבניית מחלקה‬
‫יש לשאול מספר שאלות‪:‬‬

‫מה אנחנו רוצים שהאובייקט ייצג?‬


‫מהו הממשק? )איזה הודעות הוא יקבל?(‬
‫מהו המצב הפנימי? )מהן התכונות של‬
‫האובייקט?(‬

‫‪© Eli Koren‬‬


‫מחלקה מול אובייקט‬
‫המחלקה היא אב טיפוס שממנו נייצר מופעים‬
‫שונים של האובייקט‬

PiggyBank piggy1 = new PiggyBank(5, 32);


PiggyBank piggy2 = new PiggyBank(17, 99);

piggy1 piggy2

_dollars = 5 _dollars = 17
_cents = 32 _cents = 99
PiggyBank() PiggyBank()
addMoney(…) addMoney(…)
printStatus() printStatus()

© Eli Koren
Encapsulation
public class PiggyBank {

private int _dollars;


private int _cents; declarations

public PiggyBank (int dollars, int cents) {


_dollars = dollars;
constructor
_cents = cents;
definitions
}

© Eli Koren
Encapsulation
public class PiggyBank {

public int _dollars;


public int _cents; declarations

public PiggyBank (int dollars, int cents) {


_dollars = dollars;
constructor
_cents = cents;
definitions
}

© Eli Koren
Encupsulation
public class Example {
public static void main () {
PiggyBank piggy = new PiggyBank(12, 66);
piggy.printStatus();
piggy._dollars = -12;
piggy.printStatus();
}
} You have 12 dollars and 66 cents in your piggy bank!
You have -12 dollars and 66 cents in your piggy bank!
© Eli Koren
Encupsulation
public class PiggyBank {

private
public int _dollars
_dollars;
_cents; declarations
public int _cents
private

public PiggyBank (int dollars, int cents) {


_dollars = dollars;
constructor
_cents = cents;
definitions
}

PiggyBank()
addMoney(…)
printStatus()
© Eli Koren
Encupsulation
public int getDollars () {
return (_dollars);
}
public void setDollars (int dollars) {
if (dollars >= 0)
_dollars = dollars;
else
System.out.println(“Error: You can’t enter a negative number of dollars!”);
}
public int getCents () {
return (_cents);
}
public void setCents (int cents) {
if (cents >= 0)
_cents = cents;
else
System.out.println(“Error: You can’t enter a negative number of cents!”);
}
©}Eli// end of class
Koren
Encupsulation
public class Example {
public static void main () {
PiggyBank piggy = new PiggyBank(12, 66);
piggy.printStatus();
piggy.setDollars (-12);
piggy.printStatus();
}
} You have 12 dollars and 66 cents in your piggy bank!
Error: You can’t enter a negative number of dollars!
© Eli Koren
‫יתרונות ה‪encapsulation -‬‬
‫למשתמש במחלקה אין צורך לדעת מה המימוש‬
‫הפנימי של המחלקה אלא רק מה הממשק‬

‫הזיכרון של המתכנת מוגבל וכך בפרוייקטים‬


‫גדולים הוא לא צריך לזכור את הפרטים הקטנים‬
‫של כל מחלקה‬

‫מאפשר פיצול בעיה למספר מחלקות ושימוש בכל‬


‫אחת מהן כקופסא שחורה‬

‫‪© Eli Koren‬‬


(API) ‫ממשק של מחלקה‬
‫( לדעת כדי‬client) "‫כל מה שדרוש ל"לקוח‬
‫שיוכל להשתמש במחלקה שייצרנו )כל מה‬
(public ‫שמוגדר‬
constructor for creating and initializing of the object
• PiggyBank (int dollars, int cents)
Method that adds dollars + cents to the current amount and
returns a new object with the new money amount
• PiggyBank addMoney (int dollars, int cents)
Method for printing the current amount of money in the piggy
bank
• void printStatus ()
© Eli Koren
‫‪API documentation‬‬
‫)‪(Application Programmer Interface‬‬
‫תיאור הממשק של המחלקה – איך להשתמש?‬
‫ולא איך זה מבוצע‬

‫מתייחס לכל דבר שמוגדר כ‪) public -‬קבועים‪,‬‬


‫קונסטרקטורים‪ ,‬מתודות(‬

‫תיעוד שמיועד ל‪ API -‬יתחיל ב‪ /** -‬ויסתיים ב‪*/ -‬‬

‫שימוש בתוויות שמורות כגון‪@author, :‬‬


‫‪@version, @param, @return‬‬
‫‪© Eli Koren‬‬
API -‫דוגמא ל‬
/**
* This class represents a piggy bank for savings.
*
* @author Eli Koren
* @version 7-11-06
*/
public class PiggyBank {
private int _dollars;
private int _cents;
/**
* Constructs a PiggyBank. set the initial amount of money to the given amount
* @param dollars number of dollars in the piggy bank.
* @param cents number of cents in the piggy bank.
*/

public PiggyBank (int dollars, int cents) {


_dollars = dollars;
_cents = cents;
}
© Eli Koren
/**
* Adds the given amount of money to the current amount in the piggy bank
* @param dollars number of dollars to be added to the piggy bank.
* @param cents number of cents to be added to the piggy bank.
* @return returns a new PiggyBank object containing the new amount of money
*/

public PiggyBank addMoney (int dollars, int cents) {


int newDollars = _dollars + dollars;
int newCents = _cents + cents;
if (newCents > 99) {
newDollars += newCents / 100;
newCents = newCents % 100;
}
return (new PiggyBank(newDollars, newCents));
}
/**
* Prints the current status (amount of money) of the piggy bank
*/

public void printStatus () {


System.out.println(“You have “ + _dollars + “ dollars and ” +
_cents + “ cents in your piggy bank!”);
}
©}Eli// end of class
Koren
© Eli Koren
© Eli Koren
String ‫המחלקה‬
‫ ומייצגת מחרוזת‬Java ‫מחלקה שניתנת לנו ע"י‬
‫של תווים‬

:‫המחלקה כוללת שיטות רבות בניהן‬


public char charAt(int index)
public boolean equals(Object anObject)
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

© Eli Koren
(‫ )המשך‬String ‫המחלקה‬
‫ כאשר כל תו‬,‫ הינה מחרוזת של תווים‬String ‫כל‬
‫מקבל אינדקס לפי מיקומו במחרוזת )האינדקס‬
(‫מתחיל מהמיקום האפס‬
String word = “hallelujah!";
System.out.println(word.charAt(0)); h
System.out.println(word.substring(5)); lujah!
System.out.println(word.substring(3, 7)); lelu

© Eli Koren
String ‫ של המחלקה‬API
http://java.sun.com/j2se/1.5.0/docs/api/

© Eli Koren
‫הצהרה והשמה לתוך משתנה‬
int salary;
salary = 850000
850000;

Salary

© Eli Koren
‫מאחורי הקלעים של האובייקטים‬
public class Example {
public static void main() {

PiggyBank piggy = new PiggyBank();


}
1 3
}
2
undefined
_dollars = 0
_cents = 0 undefined
addMoney(…)
printStatus() undefined
undefined
34866 undefined

34866
undefined piggy

© Eli Koren Heap Memory


(‫מאחורי הקלעים של האובייקטים )המשך‬
public class Example {
public static void main() {

PiggyBank piggy2;
}
} ?‫מה יקרה בזיכרון כתוצאה מהפקודה הנ"ל‬
undefined
_dollars = 0
_cents = 0 undefined
addMoney(…)
printStatus() undefined
undefined
34866 undefined piggy2
34866 piggy

© Eli Koren Heap Memory


public class Example {
public static void main() {
‫מבט כללי על זיכרון המחשב‬
int grade = 88;
double temp = 37.5;
PiggyBank piggy = new PiggyBank();
PiggyBank piggy2 = new PiggyBank(5, 25);
}
}
undefined
13579 piggy2
_dollars = 0 _dollars = 5
_cents = 0 _cents = 25 undefined
34866 piggy
addMoney(…) addMoney(…)
printStatus() printStatus() undefined
37.5 temp
undefined
34866 13579 undefined grade
88
undefined

© Eli Koren Heap Memory


‫מאחורי הקלעים של קריאה למתודה‬
public class Example {
public static void main() {
PiggyBank piggy = new PiggyBank();
PiggyBank betterPiggy = piggy.addMoney(5, 0);
betterPiggy.printStatus( );
}
}
You have 5 dollars and 0 cents in your piggy bank!
undefined
_dollars = 5
0
_cents = 0 undefined
addMoney(…)
printStatus() undefined
undefined
34866 47721
47721
undefined betterPiggy

34866
undefined piggy
Heap Memory
© Eli Koren
‫מאחורי הקלעים של קריאה למתודה‬
public class Example {
public static void main() {
PiggyBank piggy = new PiggyBank();
piggy = piggy.addMoney(5, 0);
piggy.printStatus( );
}
}
You have 5 dollars and 0 cents in your piggy bank!
undefined
_dollars = 5
0
_cents = 0 undefined
addMoney(…)
printStatus() undefined
undefined
34866 47721 undefined
47721
34866
undefined piggy
Heap Memory
© Eli Koren

You might also like