Virtual tables and abstract in Java

后端 未结 2 1659
小蘑菇
小蘑菇 2021-01-30 09:48

In an interview I was given the following code:

public abstract class Base {
    public int x = 1;
    public Base() {
        foo();
    }
    public abstract v         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 09:50

    Obviously, only the derived class's foo() is called.

    It prints 0 in the first time because it happens before assigning x = 2, which happens only in the constructor of Derived, after Base's initialization is complete. It prints 0 and not 1, because Derived.x is being accessed and not Base.x, and it was not initialized yet, and is still 0. The declaration of x in Derived hides the field in Base, so when Derived is printing x, it prints Derived.x.

    EDIT: activation order when creating Derived(): [schematic]

    1. create Base:
       1.1. assign Base.x = 1
       1.2. invoke foo()
          1.2.1 print Derived: Derived.x //Derived.x was not initialized here yet!
    2. assign Derived.x = 2
    

    The second is trivial and expected [in my opinion at least].

提交回复
热议问题