標籤:name this 上海 stat under 屬性 北京 tco system
static關鍵字:
package com.dingding.staticdemo;class Person{ String name; private static String country = "北京"; public Person(String name){ this.name = name; } public static String getCountry() { return country; } public static void setCountry(String country) { Person.country = country; } public void tell(){ System.out.println("姓名:"+name+" 出生地:"+country); }}public class StaticDemo01 { public static void main(String[] args) { Person.setCountry("上海");//類方法(static)一般用於所用的執行個體對象都一樣的值的情況 Person p1 = new Person("張三"); p1.tell(); Person p2 = new Person("李四"); p2.tell(); Person p3 = new Person("王五"); p3.tell(); }}
運行結果:
姓名:張三 出生地:上海
姓名:李四 出生地:上海
姓名:王五 出生地:上海
分析:
1、類方法、類變數(static)一般用於所用的執行個體對象都是一樣的值的情況。
2、在main()方法中,代碼Person.setCountry("上海");是聲明靜態,所以它要在執行個體化前進行調用。
3、類變數的特點:所有對象和類共同擁有這個屬性。
java 筆記(6) static關鍵字