类属性、类方法的设计思想

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值