الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

هل هي parameter in a method or object of a class

بدأه ledow2007 في 20 مارس 2012 · 2 رد · 685 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

class Box { // To declare a class named Box

double width; // To declare a double variable named width

double height; //To declare a double variable named height

double depth; // To declare a double variable named depth

// This is the constructor for Box.

Box(double w, double h, double d) { // Declare a method named Box contains three double var

width = w; // w mention to variable width

height = h; // h mention to variable height

depth = d; // depth mention to variable depth

}

// compute and return volume

double volume() { // double method named volume

return width * height * depth; this method (volume) return width * height * depth

}

}

class BoxDemo7 { // main class named BoxDemo7

public static void main(String args[]) { // main method

// declare, allocate, and initialize Box objects

Box mybox1 = new Box(10, 20, 15); /* ?????? What does it mean? Is it a method (if yes) where the parameters variables that we can pass arguments to them. Why did they put values directly? Or it is an object of a class. */

Box mybox2 = new Box(3, 6, 9); // ??????

double vol; // to declare a double variable named vol

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

}

}

#2

أتوقع سؤالك في هذا الأمر

Box mybox1 = new Box(10, 20, 15); /* ?????? What does it mean? Is it a method (if yes) where the parameters variables that we can pass arguments to them. Why did they put values directly? Or it is an object of a class. */ 
Box mybox2 = new Box(3, 6, 9); // ??????

 Box mybox1;

هذا يعتبر declare لـ Object جديد

و

 new Box(10, 20, 15);

هذا يعتبر إنشاء للـ Object

والقوسين هي استدعاء Constructor الموجود في الكلاس Box

 Box(double w, double h, double d)

ولو تلاحظ انه يستقبل 3 parameters

ولو مسحت w على سبيل المثال فأنت بحاجة الى مسح أحد الأرقام المرسله Constructor

فيصير الـ Constructor بهذا الشكل

 Box(  double h, double d)

وإذا أنشأت Object جديد راح يكون بهذا الشكل

 Box mybox1 = new Box(10, 20 );

الـ Constructor فائدته هي أنه يعطي قيمة ابتدائية لأي متغير أنت تريده

على سبيل المثال لو كان لدينا كلاس اسمه Car

ونريد أن ننشئ منه سيارة اسمها x1

سنكتب هذا الكود :

 public class Box {

int  speed;  

Box(int  s   ) {  
speed = s; 
System.out.print(speed);
}


public static void main(String args[]) {  

Car  x1 = new Car(180);
}

وبكذا راح تكون السرعة لكل سيارة ننشئها = 180

أتمنى تكون وصلت المعلومة

:wacko:

معلومة أخرى

الـ Constructor لا يرجع بقيمة وكتابته اختياريه على حسب البرنامج الي تبغاه

سواءً أنشأته أم لا هو يكون موجود :happy:

1
#3

Thanks so much for your support and help

مواضيع مشابهة