JAVA-static, final

In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.

这一部分,我们将讨论关键字static的使用,它用来创建的域和方法隶属于类本身,而不像通常那样隶属于实例。

例如,依据自行车蓝图,生产一系列自行车实体,每辆自行车都要有一个全球唯一序列号:

public class Bicycle {
        
    private int cadence;
    private int gear;
    private int speed;
        
    // add an instance variable for the object ID
    private int id;
    
    // add a class variable for the
    // number of Bicycle objects instantiated
    private static int numberOfBicycles = 0;

    public Bicycle(int startCadence, int startSpeed, int startGear){
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;

        // increment number of Bicycles
        // and assign ID number
        id = ++numberOfBicycles;
    }

    // new method to return the ID instance variable
    public int getID() {
        return id;
    }
    
    public static int getNumberOfBicycles() {
        return numberOfBicycles;
    }
    ...
}
The final modifier indicates that the value of this field cannot change.

关键字final指示该域的值不能改变。

static final double PI = 3.141592653589793;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值