package org.chinasoft.test;public class Person { public static String hello = "Hello Person";

private String name;


public Person() {
}

public Person(String name) {
this.name = name;
}

public String getName() {
return this.name;
}

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

}
package org.chinasoft.test;public class Student extends Person {
public static String hello = "Hello Student";

private String name;

public Student(String name) {
this.name = name;
}

/*public String getName() {
return "Student1 : " + this.name;
}*/

public void setName(String name) {
this.name = name;
}
}
测试类:
package org.chinasoft.test;public class ObjectCreate01 {
public static void main(String[] args) {
Person per = new Student("zhangsan");
System.out.println(per.getName());
System.out.println(per.hello);
System.out.println(per instanceof Student);
}
}问题:将Student中的getName注释掉之后,
per.getName()输出的结果为null,per.hello输出的结果为Hello Person,
per instanceof Student 结果为true;此时在Student中没有找到getName方法会通过反射
去找父类中的getName方法输出结果为null很正常,但per instanceof Student 结果为true,per是Student的实例
调用属性的时候为什么不去调Student类的?请友友们结合多态和反射讲解下原因!O(∩_∩)O谢谢。。

解决方案 »

  1.   

    因为你的属性 都是 静态 的,  访问静态属性时, 是根据 类 去访问的, 也就是 person 的 hello,
    静态属性 是不需要 对象的 。因为 你 声明 per 的时候 是用 person 声明的。而 静态属性 在对象 存在之前就已经有了。所以访问的是 person类里面的 hello。 而不是你 new 出来的 对象里面的。 你可以把 属性的 static 去掉, 这样 就是 student 里面的 hello 了。
     或者 声明类型时。 用Student stu  。