Class variables and class methods

Class variables and class methods

The question is: there are a group of children playing with snowmen, and new children join from time to time. How do you know how many children are playing now?

Use our existing technology to solve this problem. Package name: com haikang. static_. ChildGame. java

Idea:

  1. Define a variable count in the main method
  2. When a child joins count + +, the last count records how many children play games
package JAVA Object oriented advanced part.static_;

public class ChildGame {
    public static void main(String[] args) {
        int count = 0;
        PloyGame game = new PloyGame("Baigujing");
        game.join();
        count++;
        PloyGame game1 = new PloyGame("bitch");
        game1.join();
        count++;
        System.out.println("Total"+count+"A child joined the game!");
    }
}

class PloyGame{
    private String name;

    public PloyGame(String name) {
        this.name = name;
    }

    public void join(){
        System.out.println(name+"Joined the game!");
    }
}

Problem analysis:

  1. count is an object independent variable, which is a local variable in the main method
  2. In the future, it is inconvenient for us to access count, and OOP is not used
  3. Therefore, we introduce class variables (static variables)

Quick start to static variables

If: an int count is designed to represent the total number of people, when we create a child, we will add 1 to the count, and the count is shared by all objects. We use class variables to solve childgame Java improvement

package JAVA Object oriented advanced part.static_;

public class ChildGame {
    public static void main(String[] args) {
        //int count = 0;
        PloyGame.count++;
        PloyGame game = new PloyGame("Baigujing");
        game.join();
        //count++;
        PloyGame.count++;
        PloyGame game1 = new PloyGame("bitch");
        game1.join();
        //count++;
        PloyGame.count++;
        System.out.println("Total"+PloyGame.count+"A child joined the game!");
    }
}

class PloyGame{
    private String name;
    //Define a variable count, which is a class variable (static variable) static
    //The biggest feature of this variable is that it is shared by all object instances of PloyGame class
    public static int count = 0;

    public PloyGame(String name) {
        this.name = name;
    }

    public void join(){
        System.out.println(name+"Joined the game!");
    }
}

Static variables (class variables) are generated when the class is loaded

Before JDK8, static variables existed in the static domain of the method area. After JDK8, static variables existed in the heap

No matter where static variables exist, there are two conclusions:

  1. static variables are shared by all objects of the same class
  2. Static static variables are generated when the class is loaded

Static variables create a class object when the class is loaded. There are static variables in the class object. The scope of static variables is to the whole class

What are class variables (remember)

Class variables, also known as static variables or static attributes, are variables shared by all objects of this class. When any object of this class accesses it, it gets the same value. Similarly, when any object of this class modifies it, it modifies the same variable.

How to define variables

Define syntax:

Access modifier static data type variable name [recommended]

static access modifier data type variable name

How to access class variables

Class name Class variable name

Or object name Class variable name

Recommended: class name Class variable name

[the access permission and scope of the access modifier of static variables are the same as those of common attributes]

package JAVA Object oriented advanced part.static_;

public class VisitStatic {
    public static void main(String[] args) {
        System.out.println(StaticVar.name);
    }
}

class StaticVar{
    //Static variables are also subject to access modifiers
    //Static variables are created as the class loads
    //The object has not been created when the class is loaded, so you can use the class name Static variable names can be called directly or through object names
    public static String name = "Haikang";
}

Summary: (1) static variables should also comply with the access modifier; (2) static variables are created with class loading; (3) the object has not been created when class loading, so you can use the class name Static variable names can be called directly or through object names

Static variables create a class object when the class is loaded. There are static variables in the class object. The scope of static variables is to the whole class

**Precautions and details for the use of class variables (must be remembered) * * seven points

1. When to use class variables: when we need to make all objects of a class share a variable, we can consider using class variables (static variables): for example, define student classes and count how much money all students pay.

2. The difference between class variable and instance variable (common attribute)

Class variables are shared by all objects of the class, while instance variables are exclusive to each object

3. Static is called class variable or static variable, otherwise it is called instance variable, ordinary variable and non static variable

4. Class variables can be defined by class name Class variable name or object name Class variable names, but java designers recommend that we use class names Class variable name access.

5. Instance variables cannot pass the class name Class variable name access

6. Class variables are initialized when the class is loaded, that is, even if you do not create an object, class variables can be used as long as the class is loaded

7. The life cycle of class variables starts with the loading of the class and is destroyed with the extinction of the class

Basic introduction to class methods

Class methods are also called static methods

Syntax:

Access modifier static data return type method name () {} [recommended]

static access modifier data return type method name () {}

Call of class method:

Usage: class name Class method name or object name Class method name [provided that the access authority and scope of the access modifier are met]

Case: Statistics of total tuition fees in static mode

package JAVA Object oriented advanced part.static_;

public class StaticDetailed {
    public static void main(String[] args) {
        Student student01 = new Student("Haikang",5168);
        System.out.println(Student.fee);
    }
}

class Student{
    public static double fee = 0;//cost
    private String name;

    public Student() {
    }


    public Student(String name,double fee) {
        this.name = name;
        this.fee = fee;
    }

    public static double getFee() {
        return fee;
    }

    public static void setFee(double fee) {
        Student.fee = fee;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * 1.When a method is decorated with static, the method is static
     * 2.Static methods can access static properties (static variables)
     */
    public void showFee(){
        System.out.println("Total tuition fees received="+Student.fee);
    }
}

Classic usage scenarios for class methods

When any object related member is involved in the method, the method can be designed as a static method to improve the development efficiency.

For example, the method utils in the tool class

Summary: in the actual development of programmers, some general methods are often designed as static methods, so that we can use them without creating objects, such as printing one-dimensional arrays, bubble sorting and completing a certain calculation task

Case:

package JAVA Object oriented advanced part.static_;

public class StaticMethod {
    public static void main(String[] args) {
        //Tool classes generated using static methods
        int[] arr = {11,88,86,99,168,43,168};
        MyStaticMethod.print(arr);
        int[] sort = MyStaticMethod.sort(arr);
        MyStaticMethod.print(sort);
        System.out.println(MyStaticMethod.sum(43, 86, 168));
    }
}

//When developing your own tool class, you can make the method static and easy to call
class MyStaticMethod{
    //Print one-dimensional array
    public static void print(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+"\t");
        }
        System.out.println();
    }

    //Bubble sorting
    public static int[] sort(int[] arr){
        int tmp = 0;
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = 0; j < arr.length-i-1; j++) {
                if (arr[j]>=arr[j+1]){
                   tmp = arr[j] ;
                   arr[j] = arr[j+1];
                   arr[j+1] = tmp;
                }
            }
        }
        return arr;
    }

    //A variable that calculates several values
    public static int sum(int...n){
        int sum = 0;
        for (int i = 0; i < n.length; i++) {
            sum += n[i];
        }
        return sum;
    }
}

Notes and details on the use of class methods (remember) six points

1. Class methods and ordinary methods are loaded with the loading of the class, and the structure information is stored in the method area: class methods have no this parameter, and ordinary methods contain this parameter

2. Class methods can be called by class name or object name

3. Ordinary methods are related to objects and need to be called through object names, such as object names Method name (parameter), cannot be called by class name

4. Object related keywords, such as this and super, are not allowed in class methods. Common methods (member methods) can

5. In class methods (static methods), only static methods or static attributes can be accessed

6. Ordinary member methods can access both non static members (non static methods and non static attributes) and static members (static methods and static members)

Summary: (1) class methods and ordinary methods are loaded with the loading of the class, and the structure information is stored in the method area. (2) static methods can only access static members (static attributes and static methods) (3) non static methods can access static members and non static members (access permissions must be observed). Class methods do not have this and super keywords

Exercise:

Output what

public class Test{
	static int count = 9;
	public void count(){
		System.out.println("count="+(count++));
	}
	
	public static void main(String args[]){
		new Test().count();//9
		new Test().count();//10
		System.out.println(Test.count);//11
	}
}

Title 2: check whether there are errors in the following code. If there are errors, modify it to see how much total is equal to

class Person {
	private int id;
	private static int total = 0;
	public static int getTotalPerson(){
		id ++;//If an error is reported, the ID attribute should be changed to static, and the ID is 1
		return total;//0
	}
	
	public Person{
		total++;
		id = total;//The id is 1 and the last total is 1
	}
}

public class TestPerson{
	public static void main(String[] args){
		System.out.println("Number of total is"+Person.getTotalPerson());//0
		Person p1 = new Person();
		System.out.println("Number of total is"+Person.getTotalPerson());//1
	}
}

Title 3: check whether the following code has errors. If there are errors, modify it to see how much total equals

class Person{
	private int id;
	private static int total = 0;
	public static void setTotalPerson(int total){
		this.total = total;//Error, there is no this keyword in the static method. Comment this line
		Person.total = total;//3
	}
	public Person{
		total++;//4
		id = total;//4
	}
}

public class TestPerson{
	public static void main(String[] args){
		Person.setTotalPerson(3);
		new Person();
		//So the final total is 4
	}
}

Summary: (1) static methods, which can only access static members (member methods and member properties) (2) non static methods, which can access all members (3) still abide by the access permission rules

Keywords: Java Back-end

Added by floR on Sat, 05 Feb 2022 08:33:47 +0200