بسم الله الرحمــن الرحيم:
متغيرات الفئة ،ماهي ؟ما دورها؟هذا هو الدرس الموالي في مدخل البرمجة الكائنية في الجافا.
متغيرات الفئة او ما نسميها instance variable هي متغيرات غير مرتبطة بالكائن الذي يتم إنشائه و إنما بالنوع أو الفئة.مثلا نريد متغيرا ندرجه في فئة ما ويمكننا من تحديد عدد الكائنات التي تم إنشائها من هذه الفئة،هذا المتغير نسميه متغير الفئة.
مثال واحد أفضل دائمة من محاضرة
،نعود لمثال الفئة Car الذي أدرجناه في الدروس السابقة،سنضيف لكود الفئة متغير سنسميه number_cars كما يلي:
public class Car { //متغير الفئة
public static int number_cars=0;
private String brand;
private String color;
private int model;
public Car(){
System.out.println("Car created with default constructor");
this.brand = "";
this.color = "";
this.model = 2000;
number_cars++;//كلما تم انشاء كائن بهذا المشيد يتم زيادة قيمة المتغير
}
public Car(String _brand,String _color,int _model){
System.out.println("Car created with specific constructor");
this.brand = _brand;
this.color = _color;
this.model = _model;
number_cars++;//كلما تم انشاء كائن بهذا المشيد يتم زيادة قيمة المتغير
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getModel() {
return model;
}
public void setModel(int model) {
this.model = model;
}
}
ملاحظات أولية :
إمكانية الوصول للمتغير هي public ثم نضيف الكلمة المفتاحية static و التي تعني انها ثابتة.
تم زيادة قيمة المتغير في كل من المشيدات،يعني انه كلما انشأنا كائنا بهذه المشيدات ستزداد هذه قيمة المتغير الذي ليس خاصا بكل كاءن ،و إنما خاص بالفئة.
ننتقل للكلاس الرئيسية و ننفذ الكود التالي :
public class MainClass {
public static void main(String args[]) {
Car car1 = new Car();
Car car2 = new Car("Mercedes", "Black", 2009);
Car car3 = new Car("Golf", "White", 2010);
System.out.println("the number of created cars is "+Car.number_cars);
}
}
لاحظوا جيدا أننا عند استدعائنا للمتغير كتبنا اسم الفئة ثم نقطة ثم اسم المتغير اي Car.number_cars ولو حاولنا استدعائه تحت اسم الكائن car1 مثلا فذلاك لن يغير من الأمر شيئا،وستبقى النتيجة كما هي.
وهي كمايلي :
Car created with default constructor Car created with specific constructor Car created with specific constructor the number of created cars is 3
اتمنى ان يكون الدرس مفهوما واي اسئلة لا تنسوا التفاعل.دمتم في رعاية الله.






0 commentaires:
Enregistrer un commentaire