版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/82659448
类成员包括类变量和类方法,相对于实例变量和实例方法来说,区别是加了static关键字,所有对象使用同一份内存,访问规则如下
package com.sweetop.studycore.classes;
/**
* Created with IntelliJ IDEA.
* User: lastsweetop
* Date: 2018/9/9
* Time: 下午10:37
* To change this template use File | Settings | File Templates.
*/
public class Bicycle {
// the Bicycle class has
// three fields
private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycle = 0;
// the Bicycle class has
// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
id = ++numberOfBicycle;
}
public static int getNumberOfBicycle() {
return numberOfBicycle;
}
public int getId() {
return id;
}
// the Bicycle class has
// four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
public int getCadence() {
return cadence;
}
public int getGear() {
return gear;
}
public int getSpeed() {
return speed;
}
public Bicycle newBike() {
return new Bicycle(1, 1, 1);
}
}
- 实例方法能直接访问实例变量和实例方法
- 实例方法能直接访问类变量和类方法
- 类方法能直接访问类变量和类方法
- 类方法不能直接访问实例变量和实例方法,必须使用一个对象的引用才可以,同样类方法也不能使用this关键字,因为没有实例给this引用
虽然实例也可以指向类变量或类方法,但是一般不要这么用,这样会在是否是类变量或者类方法上产生混淆,
static有时候会和final一起使用来定义常量。
static final double PI = 3.141592653589793;
如果类型是基本类型或者字符串的话,在编译的时候,编译器就会把代码中的常量直接替换成对应的值,这种常量叫做编译时常量。因此但常量更改的话并不是只编译常量所在的类就可以了,所有使用到的地方都要重新编译,