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属性时就出现了错误。
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属性时就出现了错误。
- static
- static
- static{}
- static
- static
- Static
- static
- static
- Static
- static
- static
- static
- static
- static
- static
- static
- static
- static
- Java SE——方法重载与继承
- poj 3667 Hotel 线段树
- Windows的任务调度机制
- C++面试宝典(转)
- 单元测试
- static??
- GDB_Linux调试器
- u-boot代码学习问题和移植问题汇总
- Android中Service类onStartCommand
- centos vsftpd 553 Could not create file解决方法
- 三个标签案例:帮你深入学习JSP自定义标签
- 九大排序算法再总结
- 一篇好的软文在SEO优化中能起到多大的作用
- 使用Python语言高效地处理一个文本文件