class Student {
static String name;
public Student(){};
public Student(String name){
this.name=name;
}
public static void study(){
System.out.println(name+"is playing now!");
}
}
public class test03 {
public static void main(String [] args){
Student stu=new Student("张三");
Student st=new Student("李四");
Student.name="张三";
st.study();
stu.study();
}
}
结果都是张三 如果没有Student.name="张三";结果都是李四 为什么呢
class Student {
static String name;
public Student(){};
public Student(String name){
this.name=name;
}
public static void study(){
System.out.println(name+"is playing now!");
}
}
public class test03 {
public static void main(String [] args){
Student stu=new Student("张三");
Student st=new Student("李四");
//Student.name="张三";
Student.study();
stu.study();
}
}
结果又都是李四 作者: С呲號→佔缐 时间: 2013-4-3 08:49
name在学生类里面是静态变量,在学生类两次初始化的时候,最后一次初始化为了李四,因为static声明的属性是共享的,所以都是李四,而后面用学生类直接调用name再赋值张三,所以又变为了张三。关于内存的加载我也不是很清楚,看那个的话估计会更明了些。作者: 罗平 时间: 2013-4-3 08:52
static修饰的成员变量属于该类。
而且这个static修饰的变量是一个所有的对象都共享的变量,刚开始new张三时,那个static修饰的name,是张三,new李四的时候,将它修改成了
李四,所有最后都是李四了。如果没删Student.name="张三"; 最后就是张三。作者: 王杰123 时间: 2013-4-3 08:55
public class Student {
static String name;
public Student(){};
public Student(String name){
this.name=name;
}
public static void study(){
System.out.println(name+"is playing now!");
}
}