class Person {
public static int v = 10;
public static void showV () {
System.out.println("V = "+v);
}
public static void sell () {
v--;
}
private String name;
private String gender;
private int age;
public int getAge() {
return age;
}
public Person () {
}
public Person (String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public void say () {
System.out.println(getName()+" is saying sth");
}
}
public class T2 {
public final static void main(String[] args) {
// 使用类名直接调用静态方法
Person.showV();
Person.sell();
Person.showV();
// 使用匿名对象,在堆中开辟空间,只使用一次
new Person("xiaohong", "male", 77).say();
Person xiaoming = new Person();
Person.sell();
// 使用对象名调用静态方法,不报错,但是有警告
xiaoming.showV();
xiaoming.setName("xiaoming");
xiaoming.setAge(19);
xiaoming.setGender("male");
xiaoming.say();
}
}
运行结果:
使用静态方法的时候,只能访问其他静态方法和静态的变量
解释:
静态方法不能访问非静态的数据和方法,因为这两项都依赖于具体的实例,而静态方法在对象实例化之前就已经被JVM装载,而类中的实例变量和实例对象必须在对象开辟堆内存之后才能使用。