static??

来源:互联网 发布:免费进销存软件排名 编辑:程序博客网 时间:2024/06/01 07:30
在使用static类型声明的方法时需要注意的是:如果在类中声明了一static类型的属性,则此属性既可以在非static类型的方法中使用,也可以在static类型的方法中使用。但用static类型的属性调用非static类型的属性时,则会出现错误。
public class PersonStatic
{
String name = "张三" ;
static String city = "中国";
int age ;
public PersonStatic(String name,int age)
{
this.name = name ;
this.age = age ;
第 181 页
}
public static void print()
{
System.out.println(name);
}
public String talk()
{
return "我是:"+this.name+",今年:"+this.age+"岁,来自:"+city;
}
}
编译结果:
PersonStatic.java:13: non-static variable name cannot be referenced from a static context
System.out.println(name);
^
1 error
可以发现,程序中print()方法是static类型的,而name属性是非static类型的,所以print在调用非static类型的name属性时就出现了错误。
原创粉丝点击