java 多态奇怪现象,子类还没有构造完成就开始干活了,谁来帮我解释?
java代码:
package test.extend; public class Base { public Base(){ System.out.println("基类构造"); say(); } public void say(){ System.out.println("我是基类"); } public static void main(String[] args) { Base base=new Child(); } } class Child extends Base{ public Child(){ System.out.println("子类构造"); say(); } @Override public void say(){ System.out.println("我是子类"); } }
运行结果:
基类构造
我是子类
子类构造
我是子类
在C#中:
public class BaseA { public BaseA() { Function(); } public virtual void Function() { Console.WriteLine("Base::Function"); } } class ChildA :BaseA { public ChildA() { Function(); } public virtual void Function() { Console.WriteLine("Child::Function"); } }运行结果:
Base:Function
Child::Function
在C++中:
class BaseA { BaseA() { Function(); } virtual void Function() { cout<<"Base::Function"; cout<<endl; } } class ChildA : public BaseA { ChildA() { Function(); } virtual void Function() { cout<<"Child::Function"; cout<<endl; } } } }运行结果:
Base:Function
Child::Function
开始做,坚持做,重复做