Polymorphic method in Constructor (Java)

前端 未结 4 2062
温柔的废话
温柔的废话 2021-02-08 09:46

Class A calls the public method f() in the Constructor. Class B overrides method f() with its own implementation.

Suppose you inta

4条回答
  •  被撕碎了的回忆
    2021-02-08 10:06

    When new B(), A's Constructor is called implicitly or called via super(). Although it is defined in Class A, actually the current class is B.

    Try add the below debug info into A's constructor and functions.

    System.out.println(this.getClass());
    

    In your case, the function f() in Class A has been overriden by Class B, so the function in A() will call B()'s implementation. However, if the f() is a private method and can not be override by B, the A.f() will be called with higher priorities.

    But as others commented, it's not a good practice.

提交回复
热议问题