当前位置: 代码迷 >> J2SE >> 新手有关问题!求解决
  详细解决方案

新手有关问题!求解决

热度:129   发布时间:2016-04-24 01:26:23.0
新手问题!求解决
谁知道这代码错在哪了啊?搞了半天也没找出来。

class Person{
private String name;

void setName(String n){
this.name = n;
}


String getInfo(){
return "name is"+ this.name;
}
}

class Student extends Person{

private String school;

void setSchool(String s){
this.school = s;
}
String getInfo(){
return "name is "+ name + "; school is " + school;
}
}

public class TestPrivate{
public static void main(String[] args){
Person person = new Person();
Student student = new Student();
student.setName("bill");
student.setSchool("Peking University");
System.out.println(student.getInfo());
}
}

------解决方案--------------------
private String name;改成protected String name;才能在子类里直接访问name
------解决方案--------------------
name是private的,只能在声明这个变量的类中使用,所以可以在Person中添加一个public方法:
public String getName() {
return name;
}

然后Student的getInfo改为:
String getInfo() {
return "name is " + getName() + "; school is " + school;
}
------解决方案--------------------
Java code
class Person {    private String name;        void setName(String n) {        this.name = n;    }    String getName() {        return name;    }    String getInfo() {        return "name is" + this.name;    }}class Student extends Person {    private String school;    void setSchool(String s) {        this.school = s;    }    String getSchool() {        return school;    }    String getInfo() {        return "name is " + this.getName() + "; school is " + this.getSchool();    }}public class TestPrivate {    public static void main(String[] args) {        Person person = new Person();        Student student = new Student();        student.setName("bill");        student.setSchool("Peking University");        System.out.println(student.getInfo());    }}
------解决方案--------------------
private私有变量不能被子类直接使用,也可以在Person添加getName方法,然后在子类中直接调用
------解决方案--------------------
探讨

private私有变量不能被子类直接使用,也可以在Person添加getName方法,然后在子类中直接调用
  相关解决方案