ขณะเขียนโค้ดใดๆ ใน Java มีกฎและข้อบังคับบางชุดที่ต้องปฏิบัติตามซึ่งถือเป็นมาตรฐาน ตัวอย่างเช่น คลาสประกอบด้วยตัวแปรและฟังก์ชันต่างๆ สามารถใช้ฟังก์ชันเพื่อทำงานกับตัวแปรได้ สามารถขยายชั้นเรียนและด้นสดได้เช่นกัน
โครงสร้างพื้นฐาน
List of packages that are imported;
public class <class_name>
{
Constructor (can be user defined or implicitly created)
{
Operations that the constructor should perform;
}
Data elements/class data members;
User-defined functions/methods;
public static void main (String args[]) extends exception
{
Instance of class created;
Other operations;
}
} การทำงานของโปรแกรม Java เริ่มต้นจากฟังก์ชัน 'main' เนื่องจากไม่มีการส่งคืนใดๆ ประเภทของการส่งคืนจึงเป็นโมฆะ รหัสควรเข้าถึงได้ดังนั้นจึงเป็น "สาธารณะ"
ตัวสร้างใช้เพื่อเริ่มต้นวัตถุของคลาสที่กำหนดไว้ก่อนหน้านี้ ไม่สามารถประกาศด้วยคีย์เวิร์ด 'final', 'abstract' หรือ 'static' หรือ 'synchronized' ได้
ในทางกลับกัน ฟังก์ชันที่ผู้ใช้กำหนดจะทำงานเฉพาะและสามารถใช้กับคำหลัก "สุดท้าย", "นามธรรม" หรือ "คงที่" หรือ "ซิงโครไนซ์" ได้
ตัวอย่าง
public class Employee
{
static int beginning = 2017;
int num;
public Employee(int i)
{
num = i;
beginning++;
}
public void display_data()
{
System.out.println("The static value is : " + beginning + "\n The instance value is :"+ num);
}
public static int square_val()
{
return beginning * beginning;
}
public static void main(String args[])
{
Employee emp_1 = new Employee(2018);
System.out.println("First object created ");
emp_1.display_data();
int sq_val = Employee.square_val();
System.out.println("The square of the number is : "+ sq_val);
}
} ผลลัพธ์
First object created The static value is : 2018 The instance value is :2018 The square of the number is : 4072324
คลาสที่ชื่อ Employee มีคุณสมบัติที่แตกต่างกัน และคอนสตรัคเตอร์ถูกกำหนดให้เพิ่มหนึ่งในแอททริบิวต์ของคลาส ฟังก์ชันชื่อ 'display_data' จะแสดงข้อมูลที่มีอยู่ในคลาส ฟังก์ชันอื่นที่ชื่อ 'square_val' จะคืนค่ากำลังสองของตัวเลขที่ระบุ ในฟังก์ชันหลัก มีการสร้างอินสแตนซ์ของคลาสและเรียกใช้ฟังก์ชัน เอาต์พุตที่เกี่ยวข้องจะแสดงบนคอนโซล