วันศุกร์ที่ 20 เมษายน พ.ศ. 2555

java

เริ่มต้นการเขียนโปรแกรมด้วย Java
208
คือ ข้อมูลทุกตัวที่มีอยู่ใน class MotorVehicle เรามาดูกันถึง ข้อมูล และ method ที่เรา
กำหนดให้มีใน class MotorVehicle
1: /**
2: Class MotorVehicle
3: */
4:
5: class MotorVehicle {
6: protected String make; //e.g. Ford, Honda
7: protected String model; //e.g. Taurus, Steed
8: protected int year; //e.g. 2001, 2003
9: protected int seats; //e.g. 4, 2
10:
11: //constructor
12: MotorVehicle(String make, String model, int year, int seats) {
13: this.make = make;
14: this.model = model;
15: this.year = year;
16: this.seats = seats;
17: }
18:
19: //returns company who makes this vehicle
20: protected String getMake() {
21: return make;
22: }
23:
24: //returns model of this vehicle
25: protected String getModel() {
26: return model;
27: }
28:
29: //returns year when this vehicle is made
30: protected int getYear() {
31: return year;
32: }
33:
34: //returns number of seats this vehicle has
35: protected int getSeats() {
36: return seats;
37: }
38: }
ใน class MotorVehicle เรากำหนดให้มี constructor เพียงตัวเดียวสำหรับการสร้าง object โดย
เราเลือกใช้คำสั่ง this ในการแยกแยะตัวแปรที่อยู่ใน class กับตัวแปรที่เป็น parameter
MotorVehicle(String make, String model, int year, int seats) {
this.make = make;
this.model = model;
this.year = year;
this.seats = seats;
}

1 ความคิดเห็น: