java中的变量问题 class Person { String name; int age; public void setName(String name) {this.name = name;} public void setAge(int age) {this.age=age;} public String getName() {return name;} public int getAge() {return age;} public String getInfo() { return "Name: "+ name + "\n" +"age:"+ age;
} } class Student extends Person { private String school; public String getSchool() {return school;} public void setSchool(String school) {this.school = school;} public String getInfo() { return "Name: "+ name +"\n" +"age: "+age + "\n" +"school: "+getSchool(); }
} public class TestOverWrite { public static void main (String args[]) { Student student = new Student(); Person person = new Person(); person.setName("none"); person.setAge(1000); student.setName("john"); student.setAge(18); student.setSchool("SCH"); System.out.println(person.getInfo()); System.out.println(student.getInfo());
} }
return "Name: "+ name + "\n" +"age:"+ age;中返回的name,age指的是成员变量还是局部变量?怎么判别的?
public String getInfo() {
return "Name: "+ name + "\n" +"age:"+ age; //这里有定义局部变量吗?肯定是成员变量
}
------解决方案--------------------
------解决方案--------------------
Java code
class Person {
String name;
int age;
public void setName(String name) {this.name = name;}
public void setAge(int age) {this.age=age;}
public String getName() {return name;}
public int getAge() {return age;}
public String getInfo() {
return "Name: "+ name + "\n" +"age:"+ age;
}
}
------解决方案-------------------- 成员变量,方法里面没有同名的局部变量,如果有的话要加上this
Java code
public String getInfo()
{
String name = "XiaoBai";
int age = 12;
if (name != null)
{
return "Name: "+ name + "\n" +"age:"+ age; //这里访问的是局部变量
}
return "Name: "+ this.name + "\n" +"age:"+ this.age; //这里访问的是成员变量
}
------解决方案-------------------- 因为是在同一个类体的作用范围内,可以直接引用到name其实相当于this.name 如果放在其他类当中就不行了