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中文网其他相关文章!