class Base {
int i = 99;
public void amethod () {
System.out.println (“Base.amethod ()”);
}
}
public class RType extends Base {
int i = -1;
public static void main (String argv []) {
Base b = new RType (); //<= Note the type
System.out.println (b.i);
b.amethod ();
}
public void amethod () {
System.out.println (“RType.amethod ()”);
}
}結果:
99
RType.amethod ()提示:
注意,b 引用的类型是Base,但是实际的类型是类RType。对amethod 的调用将启动
RType 中的版本,但是b.i 输出的调用将引用Base 类中的域i。为什么是99呢?? 搞不懂!!!
int i = 99;
public void amethod () {
System.out.println (“Base.amethod ()”);
}
}
public class RType extends Base {
int i = -1;
public static void main (String argv []) {
Base b = new RType (); //<= Note the type
System.out.println (b.i);
b.amethod ();
}
public void amethod () {
System.out.println (“RType.amethod ()”);
}
}結果:
99
RType.amethod ()提示:
注意,b 引用的类型是Base,但是实际的类型是类RType。对amethod 的调用将启动
RType 中的版本,但是b.i 输出的调用将引用Base 类中的域i。为什么是99呢?? 搞不懂!!!
public String str = "SuperStr"; public void show() {
System.out.println("Super.show: " + str);
}
}class ExtendShow extends SuperShow {
public String str = "ExtendStr"; public void show() {
System.out.println("Extend.show: " + str); } public static void main(String[] args) {
ExtendShow ext = new ExtendShow();
SuperShow sup = ext;
sup.show();
ext.show();
System.out.println("sup.str = " + sup.str);
System.out.println("ext.str = " + ext.str);
}
}There is only one object, but we have two variables containing references to it: One variable has type SuperShow (the superclass) and the other variable has type ExtendedShow (the actual class). Here is the output of the example when run:Extend.show: ExtendStr
Extend.show: ExtendStr
sup.str = SuperStr
ext.str = ExtendStrFor the show method, the behavior is as you expect: The actual class of the object, not the type of the reference, governs which version of the method is called. When you have an ExtendShow object, invoking show always calls ExtendShow's show even if you access it through a reference declared with the type SuperShow. This occurs whether show is invoked externally (as in the example) or internally within another method of either ExtendShow or SuperShow.For the str field, the type of the reference, not the actual class of the object, determines which class's field is accessed. In fact, each ExtendShow object has two String fields, both called str, one of which is hidden by ExtendShow's own, different field called str
改成RType b = new RType ();
你就知道了
b.amethod ();
////这种情况下,在java中就规定,调用的是派生类中的重载了基类的方法.
但是在这里,成员变量并未被覆盖掉