如果代码中有多个名称相同的可见(可访问)变量(例如,实例变量和局部变量),则将访问局部变量。
class Main
{
public int count = 0; // 声明实例变量
public void run()
{
count = 15; // 访问实例变量
int count = 10; // 声明局部方法变量
count++; // 访问方法变量
}
}
当然也可以访问实例变量。
static(类)变量:
ClassName.variableName
// 下面是一些示例:
Cat.catsCount
-----------------------------
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;
}
}
}
非 static(实例)变量:
this.variableName
// 下面是一些示例:
this.catsCount
-------------------------------------
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() 中的年龄为 " + age);
}
}
}