构造函数中的多态方法(Java) [英] Polymorphic method in Constructor (Java)
问题描述
类 A
在构造函数中调用public方法 f()
。 B类用其自己的实现覆盖方法 f()
。
假设你intantiate Object 对象
B
的方法 f()
对象 A
,尽管对象 B
未完全初始化。
<
是的,这是不推荐的做法,但我不会不了解为什么 Java未调用
f()
基类实现 A
实现 B
,而不是伸出到 f()
代码:
A类{
A(){
System.out.println(A:constructor);
f();
}
public void f(){
System.out.println(A:f());
}
}
类B扩展A {
int x = 10;
B(){
System.out.println(B:constructor);
}
@Override
public void f(){
System.out.println(B:f());
this.x ++;
System.out.println(B:x =+ x);
}
}
public class PolyMethodConst {
public static void main(String [] args){
new B
}
}
输出 p>
A:构造函数
B:f()
B:x = 1
B:
。这是不推荐的做法,因为从你的类继承的人可能无意中破坏它。
Class A
calls the public method f()
in the Constructor. Class B overrides method f()
with its own implementation.
Suppose you intantiate Object B
.. method f()
of Object B
would be called in the Constructor of Object A
, although Object B
is not fully initialized.
Can anyone explain this behavior?
EDIT: Yes, it's not recommended practice.. yet i don't understand why Java is not calling the f()
implementation of the base-Class A
instead of "reaching out" to the f()
implementation of the derived Class B
.
Code:
class A {
A() {
System.out.println("A: constructor");
f();
}
public void f() {
System.out.println("A: f()");
}
}
class B extends A {
int x = 10;
B() {
System.out.println("B: constructor");
}
@Override
public void f() {
System.out.println("B: f()");
this.x++;
System.out.println("B: x = " + x);
}
}
public class PolyMethodConst {
public static void main(String[] args) {
new B();
}
}
Output:
A: constructor
B: f()
B: x = 1
B: constructor
You're correct, that is the way it works. It's not recommended practice though, because somebody who inherits from your class can unintentionally break it.
这篇关于构造函数中的多态方法(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!