多态方法在构造函数中的行为

package com.payton.polymorphism;

abstract class Glyph {
    abstract void draw();
    Glyph(){
        System.out.println("Glyph() before draw()");
        draw();
        System.out.println("Glyph() after draw()");
    }
}

class RoundGlyph extends Glyph{
    private int radius = 1;
    RoundGlyph(int r){
        radius = r;
        System.out.println("RoundGlyph.RoundGlyph(), radius = "+ radius);
        
    }
    void draw() {
        System.out.println("RoundGlyph.draw(), radius = "+ radius);
    }
}

public class PolyConstructors {
    public static void main(String[] args) {
        new RoundGlyph(5);
    }

}

结果:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5


执行顺序:
1、在进行其他工作之前,分配给该对象的内存会被初始化为二进制的0;
2、先调用基类的构造函数,这是会调用被覆写的draw()方法(在RoundGlyph实现),所以radius = 0
3、调用派生类的构造函数。

你可能感兴趣的:(java,工作)