静态使用注意事项:
1,静态方法只能访问静态成员。
非静态方法既可以访问静态也可以访问非静态。
2,静态方法中不可以定义this,super关键字。
因为静态优先于对象存在。所以静态方法中不可以出现this。
3,主函数是静态方法。
class StaticDemo
{
public static void main(String[] args) //3
{
show();
}
public void show()
{
System.out.println("show....");
}
}
/*
//1.
Exception in thread "main" java.lang.Error: 无法解析的编译问题:
不能对类型 StaticDemo0 中的非静态方法 show()进行静态引用
*/
class Person
{
String name;//成员变量,实例变量。随着对象的创建而存在于堆内存中
static String country = "CN";//静态的成员变量,类变量。随着类的加载而存在于方法区中
public static void show()
{
System.out.println("::::");
//this.haha();//静态方法中不能出现this关键字2
}
public void haha()
{
System.out.println("hahaha...");
}
}
class StaticDemo
{
public static void main(String[] args) //3
{
Person p = new Person();
p.haha(); //对象调用成员方法
Person.show();//类名调用静态方法,也可对象调用静态方法(不推荐)
}
}
/*
hahaha...
::::
*/