1. 设计原则
- 类属性作为该类各个对象之间共享的变量。在设计类时,分析哪些类属性不因对象的不同而改变,将这些属性设计为类属性。相应的方法设置为类方法。
- 如果方法与调用者无关,则这样的方法通常被声明为类方法,由于不需要创建对象就可以调用类方法,从而简化了方法的调用。
2. 示例
Account类:
package com.atguigu.javase.lesson5;
public class Account {
private int id;
private int balance;
private String password;
private static double interestRate;
private static int minBalance;
private static int initId = 10000;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", balance=" + balance +
", password='" + password + '\'' +
'}';
}
public Account(int balance, String password) {
id = initId++;
this.balance = balance;
this.password = password;
}
}
TestAccount类
public class TestAccount {
public static void main(String[] args){
Account account = new Account(1000,"123");
System.out.println(account);
Account account2 = new Account(2000,"456");
System.out.println(account2);
}
}