java static關鍵字 修飾變數、修飾方法
阿新 • • 發佈:2021-01-13
技術標籤:# 4.6 Javajavastatic修飾變數修飾方法
變數安照位置分 : 屬性(成員變數) vs 區域性變數
屬性(成員變數) : 例項變數 vs 類變數(static修飾的屬性)
static可以修飾: 屬性,方法,程式碼塊,內部類
static修飾屬性(類變數):
- 同一個類建立的多個物件,每個物件單獨擁有一份例項變數,共同擁有一份類變數。
- 同一個類多個物件中某個物件對類變數進行修改後,其它的物件看到的是修改後的值。
- 類變數是隨著類的載入而載入的(類載入載入一次)。例項變數是隨著物件的建立而載入的。
- 呼叫類變數的方式 :
類名.類變數名
物件名.類變數
static修飾方法(靜態方法):
- 靜態方法是隨著類的載入而載入的。
- 靜態方法中不能呼叫例項變數和非靜態方法 (原因 :因為載入時機不同。類載入的時候物件還沒有呢)
- 非靜態方法中可以呼叫類變數和靜態方法
- 靜態方法中不能使用
this
和super
關鍵字
static修飾屬性 :
- 多個物件需共同擁有該屬性時那麼使用static修飾
- 常量 :
public static final double PI = 3.14159265358979323846;
static修飾方法:
- 工具類中的方法都是靜態方法
- 有時為了呼叫類變數方法也會定義成靜態方法。
class Person{
String name;
//例項變數
int age;
//類變數
static String country;
/*
* 非靜態方法 : 非靜態方法中可以呼叫類變數和靜態方法
*/
public void info(){
System.out.println("name=" + name + " age=" + age + " country:" + country);
show();
}
/*
* 靜態方法:
* 1.靜態方法中不能呼叫例項變數和非靜態方法 (原因 :因為載入時機不同。類載入的時候物件還沒有呢)
*/
public static void show(){
// System.out.println("static show " + name);
// info();
}
}
public class StaticTest {
public static void main(String[] args) {
Person.country = "中國";
Person p1 = new Person();
p1.name = "強東";
p1.age = 46;
p1.country = "china";
Person p2 = new Person();
p2.name = "馬雲";
p2.age = 48;
// p2.country = "中國";
Person p3 = new Person();
p3.name = "化騰";
p3.age = 38;
// p3.country = "中國";
p1.info();
p2.info();
p3.info();
System.out.println("--------------------------------------------");
//類名.靜態方法名
Person.show();
}
public void info(){
}
}
執行結果:
使用示例:
/*
* 1.需求 :統計Computer建立物件的個數
*/
class Computer{
static int count = 0;
public Computer(){
count++;
}
public void show(){
System.out.println("count=" + count);
}
}
/*
* 需求: 讓id實現自增
*/
class Employee{
int id;
String name;
int age;
static int num = 0;
public Employee(String name,int age){
this.name = name;
this.age = age;
id = ++num;
}
public void show(){
System.out.println("id= " + id + " name=" + name + " age=" + age);
}
}
public class StaticTest2 {
public static void main(String[] args) {
new Computer();
new Computer();
new Computer();
new Computer();
Computer c = new Computer();
c.show();
System.out.println("----------------------------");
Employee e = new Employee("aa", 18);
Employee e2 = new Employee("cc", 28);
Employee e3 = new Employee("dd", 38);
Employee e4 = new Employee("ff", 18);
e.show();
e2.show();
e3.show();
e4.show();
}
}
執行結果: