新学习:构造方法的重载,给成员变量赋值
错误代码:
class Student {
public static void main(String[] args) {
Person p = new Person();
p.setAge(24);
p.setName(“杨洋”);
p.show();
System.out.println(“Hello World!”);
}
//静态方法中不能引用非静态变量
class Person//这个类不能嵌套在类Student中,否则报错:无法从静态上下文中引用非静态变量 this
{
private int age;
private String name;
public Person(){ //空参构造
}
public Person(String name, int age){//有参构造
this.name = name;
this.age = age;
}
public void setAge(int age){
this.age = age;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
public void show(){
System.out.println("姓名" + name + "年龄" + age);
}
}
}
修改:类Person需要从类Student中拿出来