class SubClass extends SuperClass
{
public String name = "SubClass";
}
class SuperClass
{
public String name = "SuperClass";
}
public class Demo
{
public static void main(String[] args)
{
SuperClass clz = new SubClass();
//你觉得这里输出什么?
System.out.println(clz.name);
}
}
答案为啥是 SuperClass
因为字段上面不会有多态,只有方法才会有多态。直接访问字段时是以声明类型来对待的。这里的Super是声明类型,Sub是实际类型