static变量调用是使用 类名.变量名 的格式从而修改静态变量的值。
例:
若是使用以下方法将会输出“苹果的价格为150”
public class Solution {
public static void main(String[] args) {
Apple apple = new Apple();
apple.addPrice(50);
Apple apple2 = new Apple();
apple2.addPrice(100);
System.out.println("苹果的价格为 " + Apple.applePrice);
}
public static class Apple {
public static int applePrice = 0;
public static void addPrice(int applePrice) {
Apple.applePrice=Apple.applePrice+applePrice;
}
}
}
若前面不加上 Apple. 则会输出“苹果的价格为0”
关于非static变量,则使用时使用this调用即可,例如:
public class Solution {
public static void main(String[] args) {
Person person = new Person();
System.out.println("年龄:" + person.age);
person.adjustAge(person.age);
System.out.println("调整后的年龄:" + person.age);
}
public static class Person {
public int age = 20;
public void adjustAge(int age) {
this.age = age + 20;
System.out.println("adjustAge() 中的年龄为 " + this.age);
}
}
}
其运行结果为:
总结:
- 非static用this.变量名
- static用类名.变量名