静态方法不用new 直接class.method()这样用 非静态方法必须class class1 - new class() class1.method()这样用
public class Test{ private int nostatic; private static int sstatic; public void MyMethod(){ nostatic=2;//正确,非静态方法可以访问非静态成员 sstatic=3;//正确,非静态方法可以访问静态成员 System.out.println("我是非静态方法!nostatic="+nostatic+" sstatic="+sstatic); } public static void StaticMethod(){ // nostatic=4; 不正确,静态方法不可以访问非静态成员 sstatic=5;//正确,静态方法可以访问静态成员 System.out.println("我是静态方法!sstatic="+sstatic);
}
public static void main(String[]args){
Test test=new Test(); test.MyMethod();//静态方法直接用类名调用 Test.StaticMethod();//非静态方法要先把类实例化,用对象调用
class Chinese {
static void sing() {
System.out.println("卓彬");
} void singOurCountry() {
sing();
// 类中的成员方法也可以直接访问静态成员方法
}
}public class TestChinese {
public static void main(String[] args) {
Chinese.sing();
// 上面的程序代码直接使用了"类名.成员"的格式
Chinese ch = new Chinese();
ch.sing();
// 上面的程序代码直接使用了"对象名.成员"的格式
ch.singOurCountry();
}
}
class A{
private A(){}
private static A instance = new A();
public static A makeA(){
return instance;
}
}
直接class.method()这样用
非静态方法必须class class1 - new class()
class1.method()这样用
private int nostatic;
private static int sstatic;
public void MyMethod(){
nostatic=2;//正确,非静态方法可以访问非静态成员
sstatic=3;//正确,非静态方法可以访问静态成员
System.out.println("我是非静态方法!nostatic="+nostatic+" sstatic="+sstatic);
}
public static void StaticMethod(){
// nostatic=4; 不正确,静态方法不可以访问非静态成员
sstatic=5;//正确,静态方法可以访问静态成员
System.out.println("我是静态方法!sstatic="+sstatic);
}
public static void main(String[]args){
Test test=new Test();
test.MyMethod();//静态方法直接用类名调用
Test.StaticMethod();//非静态方法要先把类实例化,用对象调用
}
}
最常见的例子是main(),在JAVA应用程序中,程序开始必须调用main().必须定义为静态方法。
2。被声明为static的变量本质上是全局变量。当声明该类的对象时,不生成static变量的副本。类的实例共享共享同一个变量。
3。声明为static的方法限制:
仅可以调用其他static方法。
只能访问static数据。
不以任何方式引用this或super.(未实例化类)
4。如果要通过计算来初始化static变量,可以声明一个static块(这个快仅在该类第一次加载时执行一次)
5。在定义static方法和变量的类的外面,仅需要 类名.static方法或变两。很全了吧