
在關鍵字的使用上,我們已經對static方法有所了解,為了防止在使用時出現一些不必要的錯誤,了解它的使用範圍是每個人都要掌握的。這篇把static的使用注意點分成兩個面向,一個是訪問的範圍,另一個是有關方法呼叫的注意,下面我們一起來看看完整的static使用注意點吧。
1.使用static方法的時候,只能存取static聲明的屬性和方法,而非static聲明的屬性和方法是不能存取的。
package com.jk.ref;
class People{
String name;
private static String country="中國";
public People(String name){
this.name=name;
}
public void tell(){
System.out.println("name:"+name+" "+"country:"+country);
}
/**
* @return the country
*/
public static String getCountry() {
return country;
}
/**
* @param country the country to set
*/
public static void setCountry(String country) {
People.country = country;
}
}
public class StaticDemo01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
People.setCountry("shanghai");
People ps1=new People("zhangsan");
//People.country="上海";
ps1.tell();
People ps2=new People("lisi");
// ps2.country="上海";
ps2.tell();
People ps3=new People("wangwu");
// ps3.country="上海";
ps3.tell();
}
} 2.父類別引用只能調父類別和子類別重寫方法,父子同名方法不會覆寫而是遮蔽。
public class TestMain {
public static void main(String[] args) {
Super sup = new Sub(); //封裝(向上造型)
sup.m1(); //父類別參考無法調子類別未重寫方法,輸出mi in Super
sup.m2();//呼叫子類別方法m2,繼承先建構父類別方法,方法名稱相同覆寫(重寫)方法,輸出m2 in Sub
Sub sub = (Sub)sup; //拆箱(向下造型)
sub.m1(); //呼叫子類別靜態方法m1,先建構父類別方法,方法名稱相同方法名稱相同遮蔽方法,輸出m2 in Sub
sub.m2();//呼叫子類別方法m2,繼承先建構父類別方法,方法名稱相同覆寫(重寫)方法,輸出m2 in Sub
}
}
class Super{ //父類別public static void m1() { //父類別靜態方法System.out.println(“m1 in Super”);
}
public void m2() { //父類別方法System.out.println(“m2 in Super”);
}
}
class Sub extends Super{ //子類別public static void m1() { //子類別靜態方法System.out.println(“m1 in Sub”);
}
public void m2() { //子類別方法System.out.println(“m2 in Sub”);
}
}以上就是java使用static的注意點,在具體操作的時候,一定不要忽略了這兩個使用事項,這也是新手練習時常遇到的出錯點。