java遺珠之類成員
版權宣告:本文為博主原創文章,未經博主允許不得轉載。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;
如果型別是基本型別或者字串的話,在編譯的時候,編譯器就會把程式碼中的常量直接替換成對應的值,這種常量叫做編譯時常量。因此但常量更改的話並不是只編譯常量所在的類就可以了,所有使用到的地方都要重新編譯,