Writing a class: fields, constructor, methods · כתיבת מחלקה: שדות, בונה, שיטות
Make your own type
- So far you used classes like
StringandMaththat Java gave you. - Now you will write your own class. A class is a plan for an object.
- An object holds data (its own values) and methods (things it can do).
יצירת סוג משלך
- עד עכשיו השתמשת בקלאסים כמו
Stringו-MathשהJava סיפקה לך. - עכשיו תכתוב קלאס משלך. קלאס הוא תוכנית לעצם.
- עצם מכיל נתונים (הערכים שלו) ו-שיטות (מה שהוא יכול לעשות).
Instance variables
- Data that each object keeps is stored in instance variables (also called fields).
- You declare them inside the class, but outside any method.
- Each object gets its own copy of these variables.
משתני מופע
- נתונים שכל אובייקט שומר מאוחזים במשתני מופע (הנקראים גם שדות).
- אתה מגדיר אותם בתוך הקלאס, אך מחוץ לכל שיטה.
- לכל אובייקט יש העתק משלו של משתנים אלו.
public class Dog {
String name; // instance variable
int age; // instance variable
}
A constructor
- A constructor sets up a new object. It runs when you write
new. - It has the same name as the class and no return type (not even
void). - Use the word
thisto mean "this object's own variable".
יוצר (Constructor)
- יוצר מקיים אובייקט חדש. הוא פועל כאשר כותבים
new. - יש לו אותו שם כמו המחלקה ואין לו סוג החזרה (גם לא
void). - השתמש במילה
thisכדי לרמוז ל"המשתנה של האובייקת עצמו".
public class Dog {
String name;
int age;
// Constructor: runs when we make a new Dog
public Dog(String name, int age) {
this.name = name; // this.name is the field; name is the parameter
this.age = age;
}
}
Instance methods
- An instance method is an action an object can do.
- It can read and change the object's own instance variables.
- You call it on an object with a dot:
myDog.speak().
שיטות מופע
- שיטת מופע היא פעולה שאובייקט יכול לבצע.
- היא יכולה לקרוא ולשנות את משתני המופע של האובייקת עצמו.
- קוראים לה באמצעות נקודה על אובייקט:
myDog.speak().
public class Dog {
String name;
int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
// Instance method: returns a sentence about this dog
public String describe() {
return this.name + " is " + this.age;
}
}
Make and use an object
- Use
new ClassName(...)to build an object. This calls the constructor. - Store it in a variable whose type is the class name.
- Then call its methods with a dot.
יצירה ושימוש באובייקט
- השתמש ב
new ClassName(...)ליצירת אובייקט. פעולה זו קוראת ליוצר. - אחסן אותו במשתנה whose type is the class name.
- לאחר מכן קרא לשיטות שלו באמצעות נקודה.
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex", 4);
System.out.println(d.describe()); // Rex is 4
}
}
class Dog {
String name;
int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String describe() {
return this.name + " is " + this.age;
}
}
Why this?
- A parameter and a field can have the same name (like
name). - Inside the constructor,
namemeans the parameter;this.namemeans the field. thisalways means the object the method was called on.
מדוע this?
- פרמטר ושדה יכולים להיות באותו שם (כמו ⟨
name⟩). - בתוך היוצר,
nameמייצג את הפרמטר;this.nameמייצג את השדה. thisתמיד מייצג את האובייקט עליו נקראה השיטה.
Common mistakes
- A constructor has no return type and matches the class name.
- Use
this.fieldto tell a field from a parameter of the same name.
טעויות נפוצות
- למבנה בונה אין סוג החזרה והוא תואם את שם המחלקה.
- השתמש ב
this.fieldכדי להבדיל בין שדה לפרמטר בעל אותו שם.
Now you try
- Each task gives you a class skeleton with a TODO. Fill it in so it compiles and works.
- A hidden Harness builds your object and checks the results.
- Press Run to compile, then Check answer.
כעת תנסו בעצמכם
- כל משימה מספקת לך תבנית מחלקה עם TODO. מלא אותה כך שתקווד יתקפל ויעבוד.
- Harness נסתר בונה את האובייקט שלך ובוקר את התוצאות.
- לחץ על Run להתקפלה, ולאחר מכן לחץ על Check answer.
Complete the Counter class. It has an int field count that starts at 0. increment() adds 1 to it. getCount() returns the current value. · השלם את המחלקה Counter. יש לה שדה int בשם count שערכו ההתחלתי הוא 0. השיטה increment() מוסיפה 1 לשדה. השיטה getCount() מחזירה את הערך הנוכחי.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete the Rectangle class. The constructor takes width w and height h and stores them. area() returns width times height. perimeter() returns 2 times (width plus height). · השלם את מחלקת Rectangle. הבונה מקבל רוחב w וגובה h ומאחסן אותם. area() מחזיר רוחב כפול גובה. perimeter() מחזיר 2 כפול (רוחב פלוס גובה).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete the Greeter class. The constructor takes a String name and stores it in the field name. greet() returns the text Hello, followed by the name and a ! (for "Ana" it returns Hello, Ana!). · השלם את מחלקת Greeter. הבונה מקבל טקסט String name ומאחסן אותו בשדה name. greet() מחזיר את הטקסט Hello, שלאחריו השם והמילה ! (עבור "Ana" הוא מחזיר Hello, Ana!).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.