Static variables and static methods

static variable

For example, there is a bank account account class, account has three member variables, account name, savings amount and interest rate.
We know that everyone's account name and savings amount are different, but the interest rate is the same.
This interest rate is a static variable.
Static variables are staticdecorated with keywords

Static variables are public to the entire class and not independently belong to a certain class object, so static variables can be accessed directly using the class name or using an object.

// account.java
package Java;

public class account {
    
    
    // 实例变量账户金额
    double amount = 0.0;
    // 实例变量账户名
    String owner;

    // 静态变量利率
    static double interestRate = 0.0688;

    // 静态方法

    public static double interestRy(double amt) {
    
    
        // 静态方法可以访问静态变量和其他静态方法
        
        return interestRate * amt;
    }
    static {
    
    
        System.out.println("the static code is being executing\n");
        interestRate=0.0668;
    }

    // 实例方法
    public String messageWith(double amt) {
    
    
        // 实例方法可以访问实例变量、实例方法、静态变量和静态方法
        double interest = account.interestRy(amt);
        StringBuilder sb = new StringBuilder();
        // 拼接字符串
        sb.append(owner).append("'s interest is ").append(interest);
        // 返回字符串
        return sb.toString();
    }
}

package Java;

public class use {
    
    
    public static void main(String[] args) {
    
    
        //
        System.out.println((account.interestRate));
        //
        System.out.println((account.interestRy(1000)));
        account myAccount = new account();
        //
        myAccount.amount = 1000000;
        myAccount.owner = "lmy";

        System.out.println(myAccount.interestRate);
        System.out.println(myAccount.messageWith(1000));

    }
}

static method

Static methods can access static variables and other static methods, but not instance methods
Instance methods can access instance variables, other instance methods, static variables, and static methods

Guess you like

Origin blog.csdn.net/qq_52109814/article/details/123223665