静态方法:属于类本身。
非静态方法:属于类生成的每个对象。
如果一个方法与依赖于类的个别特征,应该保持静态。否则应该定义为非静态。
public class MethodDemo {
public static void main(String[] args) {
ClassA c = new ClassA(10);
System.out.println(c.noStaticMethod());
ClassA.staticMethod();
// c.staticMethod();
// 也能调用不过会引发歧义,有可能会误认为这个方法属于对象
}
}
class ClassA {
private int i;
public ClassA(int i) {
this.i = i;
}
public static void staticMethod2() {
System.out.println("staticMethod2");
}
public static void staticMethod() {
staticMethod2();// 静态方法可调用静态方法
// this.noStaticMethod();静态方法不能调用非静态方法
System.out.println("staticMethod");
}
public int noStaticMethod() {
ClassA.staticMethod();// 非静态方法可调用静态方法
return i + 1;
}
}
静态变量与非静态变量定义类似。
public class Var_Demo {
public static void main(String[] args) {
System.out.println(Person.eyeNum);// 0
Person p = new Person();
p.name = "jack";
// p.eyeNum = 2;对象也可访问类变量
Person.eyeNum = 2;
Person p2 = new Person();
System.out.println(p.eyeNum + " " + p2.eyeNum);
}
}
class Person {
String name;
static int eyeNum;// 静态变量系统默认赋初值
}
成员变量与局部变量同名时
public class Var_Demo2 {
private static int a = 100;
public static void main(String[] args) {
int a = 50;
System.out.println(a);
System.out.println(Var_Demo2.a);
// 局部变量与成员变量同名,成员变量会被覆盖(引用类型也一样)
}
}
变量使用规则
- 描述某个类中的固有信息,使用成员变量。若这个属性为对象共有的相同属性这定义为静态变量。不相同的值则使用实例变量
- 保存该类或实例运行的状态信息使用成员变量
- 某个信息需要在某个类的多个方法中共享,使用成员变量