
在关键词的使用上,我们已经对static方法有所了解,为了防止在使用时出现一些不必要的错误,了解它的使用范围是每个人都要掌握的。本篇把static的使用注意点分为两个方面,一个是访问的范围,另一个是有关方法调用的注意,下面我们一起来看看完整的static使用注意点吧。
1、使用static方法的时候,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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);
}
public static String getCountry() {
return country;
}
public static void setCountry(String country) {
People.country = country;
}
}
public class StaticDemo01 {
public static void main(String[] args) {
People.setCountry( "shanghai" );
People ps1= new People( "zhangsan" );
ps1.tell();
People ps2= new People( "lisi" );
ps2.tell();
People ps3= new People( "wangwu" );
ps3.tell();
}
}
|
2、父类引用只能调父类和子类重写方法,父子同名方法不会覆盖而是遮蔽。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class TestMain {
public static void main(String[] args) {
Super sup = new Sub();
sup.m1();
sup.m2();
Sub sub = (Sub)sup;
sub.m1();
sub.m2();
}
}
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的注意点,在具体操作的时候,一定不要忽略了这两个使用事项,这也是新手练习时经常遇到的出错点。更多Java学习指路:java教程