本帖最后由 NewDemo 于 2014-5-4 00:40 编辑
{:2_31:}困惑一天了,当局者迷,求搭救
- class Base {
- private int i = 2;
- Base() {
- System.out.println("base:" + this.i); //
- this.display();// 这里是创建子类对象时构造函数用到了父类的构造函数所以调用到了父类自身的方法,结果却是调用了子类的方法,怎么这里会出现覆盖呢?
- this.show();// 如果上句存在覆盖,那么这句话如何解释?
- }
- public void display() {
- System.out.println("base display:" + this.i);
- }
- public static void show() {
- System.out.println("base show");
- }
- }
- class Derived extends Base {
- public int i = 22;
- public Derived() {
- super();
- i = 222;
- }
- public void display() {
- System.out.println("derived display:" + i);
- }
- public static void show() {
- System.out.println("derived show");
- }
- }
- public class Test3 {
- public static void main(String[] args) {
- new Derived().display();
- // 打印结果:base:2
- // derived display:0
- // base show
- // derived display:222
- Base base = new Derived();// 父类引用指向子类对象,典型的多态
- base.show();
- base.display();// 多态,子类方法覆盖了父类方法,所以运行了子类的方法
- // 打印结果:base:2
- // derived display:0
- // base show
- // base show
- // derived display:222
- }
- }
复制代码
|