Sufficiency Economy
Group Blog
 
All blogs
 
LOVE JAVA : Day3 ทดลอง Constructor

หน้า 147

เรามี blue print  (class) แล้วสร้าง object ด้วยคำสั่ง new แต่เขาใช้คำว่า สร้าง instance

ซึ่งภายใน object หรือ instance จะมี สองอย่าง คือ data member และ method

การกำหนดค่าเริ่มต้นให้กับ data member ใน instance ทำด้วยการสร้าง method ชื่อเดียวกับ class แต่ห้ามใช้ modifier private default เพราะจะต้องถูกเรียกจากนอก class ไม่เชื่อลองดู error แน่นอน ^ ^

class Student
{
 public int id;
 private String name;
 private double gpa;
 private String school;
 
 Student(String s) {school = s;}
 
 public void setName(String n) {name = n;}
 public String getName() {return name;}
 
 public void setGpa(double g) {gpa = g;}
 public double getGpa() {return gpa;}
 
 public void setSchool(String s) {school = s;}
 public String getSchool() {return school;}
 
}

1) เพิ่ม constructor ไม่มี modifier อะไรนำหน้า ส่งค่า ชื่อโรงเรียนเป็นค่าเริ่มต้น

2) เพิ่ม data member ชื่อ school เข้าไป

3) เพิ่ม method : set get ด้วย

class StudentTest
{
 public static void main(String grgs[])
 {
  Student x = new Student("ABC school");
  x.id = 120;
  x.setName("John");
  x.setGpa(4.00);

  System.out.println(x.id+","+x.getName()+","+x.getGpa()+","+x.getSchool());
 }

}

ทำได้ สามวันแล้วววว




Create Date : 22 พฤษภาคม 2557
Last Update : 22 พฤษภาคม 2557 19:48:57 น. 0 comments
Counter : 1018 Pageviews.

ชื่อ :
Comment :
  *ใช้ code html ตกแต่งข้อความได้เฉพาะสมาชิก
 

wink99_th
Location :
พิษณุโลก Thailand

[Profile ทั้งหมด]

ฝากข้อความหลังไมค์
Rss Feed
Smember
ผู้ติดตามบล็อก : 8 คน [?]




New Comments
Friends' blogs
[Add wink99_th's blog to your web]
Links
 

 Pantip.com | PantipMarket.com | Pantown.com | © 2004 BlogGang.com allrights reserved.