Home  >  Article  >  Java  >  How to use static fields and static methods in Java

How to use static fields and static methods in Java

PHPz
PHPzforward
2023-04-25 20:43:06725browse

    First look at the following string of code:

    public class Main {
        public static void main(String[] args) {
            System.out.println("Hello, WOrld!");
        }
    }

    Our main method is marked static modifier, then what is the meaning of static modifier?

    1. Static variables

    If a field is defined as static, then each class has only one such field.

    Let’s first look at the class without static static traversal:

    class Student {
      int stuId;
      String name;
      String school = "HY No.1 High School";
    }

    Assume that there are 1500 students in the high school. The above code now creates all instance data members every time the object is created. memory will be obtained.

    All students have their unique stuId and name, these instance data members are correct in this case, they are all unique after all.

    However, "school" here is a common attribute of all objects. If it is not declared as a static variable, it will also occupy a lot of memory. But if we make it static, this field will only get memory once.

    Static variable declaration

    class Student {
      int stuId;  // 实例变量
      String name;
      static String school = "HY No.1 High School"; // 静态变量
    }

    If you declare any variable as static, it is called a static variable.

    • Static variables can be used to refer to properties common to all objects (not unique to each object), for example, an employee's company name, a student's college name, etc.

    • Static variables only obtain memory once in the class area when the class is loaded.

    Static variable test

    Code test:

    package com.yuzhou1su.RelearnJava;
    
    class Student {
        int stuId; 
        String name;
        static String school = "HY No.1 High School";
      
        Student(int id, String n) {
            stuId = id;
            name = n;
        }
    
        void display() {
            System.out.println("Student id:" + stuId + ", Name:" + name + " is from " + school);
        }
    }
    
    public class TestVariable {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Student s1 = new Student(001, "Karsa");
            Student s2 = new Student(002, "Ellen");
    
            s1.display();
            s2.display();
        }
    
    }

    Execution result:

    Student id:1, Name:Karsa is from HY No.1 High School
    Student id:2, Name:Ellen is from HY No.1 High School

    static A variable gets memory only once, if any object changes the value of the static variable, it will retain its value.

    Look at the following code:

    package com.yuzhou1su.RelearnJava;
    
    public class StaticVariableCount {
      
      static int count = 0;
      
      StaticVariableCount() {
        count++;
        System.out.println(count);
      }
    
      public static void main(String[] args) {
        // TODO Auto-generated method stub
        StaticVariableCount svc1 = new StaticVariableCount();
        StaticVariableCount svc2 = new StaticVariableCount();
        StaticVariableCount svc3 = new StaticVariableCount();
        
      }
    }

    Test result:

    1
    2
    3

    2. Static method

    A static method in Java is a method that belongs to a class, but is not considered an instance of the class; on the contrary, a static method in Java can be very Easily created and implemented without requiring any instance calls. Static methods can access any data member in the class, can perform any operation on the data member, and can take any value as input. Although the member variable to be accessed should have the scope of the variable in the class, the method can only be static.

    public static void syntax_ex (String_name) {
        Body of the program for execution.
    }
    • public. The access modifier of this class is public.

    • static. The scope of a method is static, which means that all member variables and return types are in static scope.

    • void. This keyword in the syntax flow indicates that no return type is processed in the current method.

    • syntax_ex. The name of the class, indicating that the static method is part of the currently defined class, followed by the string name.

    • body. It includes the entire core logic or business logic (if required in static mode).

    If you use static keyword on any method, it is called static method,

    Static method:

    • Static methods belong to the class, not the objects belonging to the class.

    • Static methods can be called without creating an instance of the class.

    • Static methods can access static data members and change their values.

    Static method testing

    What if we want to change the operation of learning names? You can declare a static method.

    package com.yuzhou1su.RelearnJava;
    
    class Student {
        int stuId; 
        String name;
        static String school = "HY No.1 High School";
        
        static void changeSchool() {
            school = "HY No.5 High School";
        }
      
        Student(int id, String n) {
            stuId = id;
            name = n;
        }
    
        void display() {
            System.out.println("Student id:" + stuId + ", Name:" + name + " is from " + school);
        }
    }
    
    public class TestVariable {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            Student.changeSchool();
            Student s1 = new Student(001, "Karsa");
            Student s2 = new Student(002, "Ellen");
    
            s1.display();
            s2.display();
        }
    
    }

    Test result:

    Student id:1, Name:Karsa is from HY No.5 High School
    Student id:2, Name :Ellen is from HY No.5 High School

    How static methods work

    • Static methods and instance methods are two methods in Java, They create some confusion among programmers, but it's just a misunderstanding. There is a big difference between static methods and instance methods. Let’s see how static methods work in Java. A static method in Java is a method that resides in a class and can be accessed even if the object is not created or instantiated. You can access any instance of the class by appending the name of the method to the class name and passing the parameters.

    • It can be expressed as ClassName.methodName(arguments). Furthermore, these methods are composed with the goal that the method should be shareable with all member variables and everyone's objects in the class, with its scope defined by the modifier static. These methods do not have any overloading capabilities; instead, they can be overloaded at compile time using the compiler's static binding whenever the programmer needs to share a common piece of code among all instances, objects, or member variables of the class Static methods come to the rescue because they create a shared provision for all members, objects, and variables by creating a common static scope.

    • 一个类的所有静态字段都可以使用静态字段作为一个类的静态方法的一部分进行访问。另外,静态方法也与内存分配功能有关,并且也是可以支持的。它将静态方法字段和变量的一部分与一些永久生成的堆存储在内存中,用于关联值。内存分配不支持对象作为静态方法堆的创建,或者方法本身不支持实例化。但接下来的问题是,静态方法是如何通过共享和创建所有成员的范围作为类的一部分来工作的。

    为什么 Java Main 方法是静态方法

    这是因为对象不需要调用静态方法。如果是非静态方法,JVM 会先创建一个对象,然后调用 main() 方法,这会导致额外内存分配的问题。

    main 方法不对任何对象进行操作,事实上,在启动程序时还没有任何对象。静态的 main 方法将执行并构造程序所需要的对象。

    三、静态常量

    静态变量使用的比较少,但静态常量却很常用。比如 Math 类中定义一个静态常量:

    public class Math {
      public static final double PI = 3.14159265358979;
    }

    然后在程序中,可以用 Math.PI 来访问这个常量。

    四、总结

    Java 中为什么需要静态变量?

    答:每当我们希望为一个类的所有对象拥有一个公共属性时,我们就使用一个类级别的变量,即静态变量。

    在类加载时,此变量仅在内存中加载一次。 由于它不是在Java中按对象定义的,因此可以节省内存。

    为什么用 Java 创建静态变量不是一个好习惯?

    答:静态变量是类的所有对象共有的。 如果创建了新对象,则无需测试静态变量的值。 使用静态变量的任何代码都可以处于任何状态。 它可以在新对象内或在类级别。 因此,静态变量的范围在Java类中是开放式的。

    如果我们希望对范围进行更严格的控制,则变量应在对象创建级别创建。

    同样,定义静态变量也不是一个好习惯,因为它们违反了面向对象编程的原理。

    Java 中静态方法的目的?

    答:Java 提供了静态方法的功能来在类级别创建行为。 静态方法是类的所有对象所共有的。 我们不需要创建类的任何对象来调用静态方法。 因此,它提供了不创建用于调用它的对象的便利。

    静态方法也可以访问和修改静态数据成员。 这也有助于在类级别上保持行为和状态。

    为什么在 Java 中将 main 方法标记为静态方法?

    答:Java 中的 main 方法被标记为静态,因此 JVM 可以调用它来启动程序。 如果 main 方法不是静态的,那么Java进程将调用哪个构造函数?

    因此,在Java中将主要方法标记为静态是众所周知的约定。 但是,如果我们去除static,那将会有歧义。 Java进程可能不知道要调用哪个类的方法来启动程序。

    因此,此约定有助于 Java 进程识别类中作为参数传递给 Java 进程的程序的启动代码。

    在什么情况下我们使用静态块?

    答:有时,有一个具有静态成员变量的类。 这些变量需要一些复杂的初始化。 这时,静态块可作为初始化复杂静态成员变量初始化的工具。静态块甚至在执行main之前执行。有时,我们也可以用静态的类方法替换静态块。

    是否可以在不定义main()方法的情况下执行程序?

    答:不,从Java 7开始,您需要main()方法来执行程序。 在Java的早期版本中,有一种解决方法可用于使用静态块执行。 但是现在这个差距已经缩小。

    当main方法的签名中未提及static修饰符时会发生什么?

    答:根据Java规范,main方法必须标记为静态。 它只需要一个字符串数组的参数即可。

    程序可以使用非静态方法进行编译。 但是在执行时会给出NoSuchMethodError。

    Java中的静态方法和实例方法有什么区别?

    答:通常,需要为不依赖于对象成员变量的类定义行为。 这种行为是通过静态方法捕获的。 如果存在依赖于对象成员变量的行为,则我们不会将其标记为静态,而是将其保留为实例方法。

    要调用为静态方法,我们不需要创建对象。 我们只用类名来称呼它。 但是要调用实例方法,我们需要先创建/获取一个对象。

    实例成员变量不能通过静态方法访问。 但是实例方法可以调用实例变量和静态变量。

    The above is the detailed content of How to use static fields and static methods in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete