Java中的靜態方法是屬於類別的一部分但不被視為類別的實例的方法;相反,Java 中的靜態方法可以輕鬆建立和實現,而無需任何實例呼叫。靜態方法可以存取類別的任何資料成員,並且可以對資料成員進行任何操作,或者可以將任何值作為輸入,儘管要存取的成員變數應該具有類別中變數的範圍,並且方法只能是靜態的。
開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
文法:
靜態方法在Java中的表示如下:
public static void syntax_ex (String_name) { Body of the program for execution. }
下面給出了 Java 中靜態方法的範例:
該程式演示了靜態類別及其特定成員,它試圖糾正所提到的主題中的分數;基本上,它表明在不創建任何物件或沒有任何實例化的情況下,它能夠創建和訪問靜態範圍內的類別的欄位或成員變數。
代碼:
public class E_Static_Method_Ex { int roll_no; String stdnt_name; static String subject = "Maths"; public void rectify() { subject = "English"; } E_Static_Method_Ex(int roll, String name) { roll = roll_no; name = stdnt_name; } void represent() { System.out.println(roll_no+""+stdnt_name+""+subject); } public static void main(String[] args) { String mrks = E_Static_Method_Ex.subject; System.out.println(mrks); } }
輸出:
This program demonstrates a very significant point which needs to be kept in mind while executing any static method code, which is like the arguments passed and declared in the class should be defined within the scope of static or should have initialized with the static keyword so that accessing the field or the member variable becomes easy and there remains no compilation error as represented in the given program.
Code:
public class Restrcn_Static_Class { int bi = 30; String name = "Welcome Everyone!"; public static void main(String[] args) { System.out.println(bi); System.out.println(name); } }
Output:
This program demonstrates the static variable that becomes accessible for the static class if the fields are declared and defined with static as a modifier; otherwise, the scope of static won’t get satisfied, and it will throw compilation error like the earlier example.
Code:
public class Static_Var_1 { static int cnt=0; Static_Var_1(){ cnt++; System.out.println(cnt); } public static void main(String[] args) { Static_Var_1 d1=new Static_Var_1(); Static_Var_1 dd2=new Static_Var_1(); Static_Var_1 dd3=new Static_Var_1(); Static_Var_1 dd4=new Static_Var_1(); Static_Var_1 dd6=new Static_Var_1(); } }
Output:
Static Method in Java is a useful method in a class and has a clear difference when compared with the instance method as static method gives programmers flexibility by making them free from object creation, i.e. from the method of object instantiation. It helps in making the entire static class dynamic and versatile in nature, unlike the instantiation method.
以上是Java中的靜態方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!