- package com.thinkjoy.test;
- class Base {
- String name = "Base";
- void doSomething() {
- System.out.println(this.name + "is doing Base's job.");
- }
- }
- class Derived extends Base {
- String name = "Derived";
- void doSomething() {
- System.out.println(this.name + "is doing Derived's job.");
- }
- }
- public class ThinkJoyTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Base b=new Derived();
- System.out.println(b.name);
- b.doSomething();
- Base b1=b;
- System.out.println(b1.name);
- b1.doSomething();
- Derived d=(Derived)b1;
- System.out.println(d.name);
- d.doSomething();
- }
- }
- 问输出?
答:
Base
Derivedis doing Derived's job.
Base
Derivedis doing Derived's job.
Derived
Derivedis doing Derived's job.
分析原因:
b是由Base类声明的,调用Derived构造函数生成的对象,在直接引用b中的属性时,会输出Base中定义的属性。
相反,在调用b中的方法时,调用的是Derived中重写的方法。
- 出处:http://blog.csdn.net/vector_yi/article/details/21516597