Contents
8.7. 静态方法和静态变量¶
Account.java
package com.a51work7;
public class Account {
// 实例变量账户金额
double amount = 0.0;
// 实例变量账户名
String owner;
// 静态变量利率
static double interestRate = 0.0668;
// 静态方法
public static double interestBy(double amt) {
// 静态方法可以访问静态变量和其他静态方法
return interestRate * amt;
}
public String messageWith(double amt) {
// 实例方法可以访问实例变量、实例方法、静态变量和静态方法
double interest = Account.interestBy(amt);
StringBuilder sb = new StringBuilder();
// 拼接字符串
sb.append(owner).append("的利息是").append(interest);
// 返回字符串
return sb.toString();
}
}
HelloWorld.java
package com.a51work7;
public class HelloWorld {
// 访问静态变量
public static void main(String[] args) {
// 访问静态变量
System.out.println(Account.interestRate); ①
// 访问静态方法
System.out.println(Account.interestBy(1000)); ②
Account myAccount = new Account();
// 访问实例变量
myAccount.amount = 1000000;
myAccount.owner = "Hujianli";
// 访问实例方法
System.out.println(myAccount.messageWith(1000));
// 通过实例访问静态变量
System.out.println(myAccount.interestRate); ⑥
}
}
输出信息:
0.0668
66.8
Hujianli的利息是66.8
0.0668
调用静态变量或静态方法时,可以通过类名或实例名调用。
代码第①行Account.interestRate通过类名调用静态变量,
代码第②行Account.interestBy(1000)是通过类名调用静态方法。
代码第⑥行是通过实例调用静态变量。