public class Person {
String name="person";
public void shout(){
System.out.println(name);
}
}public class Student extends Person{
String name="student";
String school="school";

}public class Test { public static void main(String[] args) {
// TODO Auto-generated method stub
Person p=new Student();
p.shout();
}}为什么这里输出的是 person 而不是 student呢?

解决方案 »

  1.   

    public class Student extends Person {
    Student(){
    this.name = "student";
    String school = "school";
    }
    }
      

  2.   

    需要在Student的构造函数中,对name重新赋值。
      

  3.   

    student 的 name 要重新 构造。
    还有你是想实现接口吧。这个模式是接口模式。
      

  4.   

    试试
    public class Person {
        String name="person";
        public void shout(){
            System.out.println(getName());//相当于this.getName(),属性相当于this.name 方法重写 属性隐藏 this类似于 Person this = new Student() this是Person类型引用 
        }
        public String getName()
        {
               return name;
        }
    }public class Student extends Person{
        String name="student";
        String school="school";
        
    }public class Test {    public static void main(String[] args) {
            // TODO Auto-generated method stub
            Person p=new Student();
            p.shout();
        }}
      

  5.   

    弄错了 子类还要重写getName
      

  6.   

    子类没有重写 shout 方法的情况下 是调用父类的 shout 方法 而 父类的 shout 方法 是调用Person类的 name 是不是相当于 
    public class Student extends Person{
    String name="student";
    String school="school"; public void shout(){
    System.out.println(super.name);
    }
    }
     可以这样理解吗
      

  7.   

    interface Say {
    public abstract void shout();
    }class Person {
    String name = "Person";
    }class Student extends Person implements Say { String name = "Student"; @Override
    public void shout() {
    // TODO Auto-generated method stub
    System.out.println(name);
    }
    }class Teacher extends Person implements Say {
    String name = "Teacher"; @Override
    public void shout() {
    // TODO Auto-generated method stub
    System.out.println(name);
    }
    }public class Main {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Say personSay;
    personSay = new Student();
    personSay.shout();

    personSay = new Teacher();
    personSay.shout(); }}
    // result:
    /*
    Student
    Teacher
    */
      

  8.   

    原因很简单:就是你的shout()方法也是person那继承过来的。。上面的代码希望能增加你对多态的理解。