public class Person {
private String name;
private int age;
private static String country = "China";
Person(String name, int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void speak(){
System.out.println(this.name+" "+this.age);
}
public static void showCountry(){
System.out.println("country is"+country);
}
}
public class TestDemo {
public static void main(String[] args) {
Person person = new Person("小王", 25);
person.setName("王小明");
}
}
當執行main()函數時,會先在棧內存中開闢一塊空間,主函數中有一個變量person,此時,方法區中會開闢一塊專屬於Person類的空間,裏面有靜態變量country,setName(String name)、speak()、showCountry()函數,new Person(“小王”,25)時,會在堆內存中開闢空間,並且將內存地址賦給person變量;當執行person.setName(“王小明”);時,setName()方法入棧,此方法中會有兩個變量,一個是this,並且將創建出來的Person對象的內存地址賦給this;一個是name,name = “王小明”。執行this.name = name;時,會將堆內存中的對象實例中的name屬性賦值爲“王小明”。