Java程式的結構和成員


編寫任何 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’ 函式開始。因為它不返回任何值,所以它的返回型別是 void。它應該可以被程式碼訪問,因此它是 ‘public’。

建構函式用於初始化先前定義的類的物件。它們不能用關鍵字 ‘final’、‘abstract’、‘static’ 或 ‘synchronized’ 宣告。

另一方面,使用者定義的函式執行特定任務,並且可以使用關鍵字 ‘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’ 的函式返回特定數字的平方。在 main 函式中,建立類的例項並呼叫函式。相關的輸出顯示在控制檯上。

更新於:2020年7月13日

200 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.