问题描述
在Java中,可以放心地假设在用作基类的类的构造函数中调用 getClass()
将提供有关派生类的信息,而不是基类的类?
In Java, is it safe to assume that getClass()
called inside a constructor of a class used as a base class will provide information about the derived class, rather than the class of the base class?
它似乎工作,但我想这不一定意味着它的安全。
例如,如果我有以下两个类:
It seems to work, but I guess that doesn't necessarily mean it's safe.For example, if I have the following two classes:
public class Parent {
public Parent() {
System.out.println(getClass().getName());
}
}
和:
public class Derived extends Parent {
public Derived() {
super();
}
public static void main(String... args) {
new Derived();
}
}
当我运行 main ()
方法在它打印的Derived类中: Derived
(这是我希望的)。但是我可以依靠JVM上的这种行为吗?
When I run the main()
method in the Derived class it prints: Derived
(which is what I was hoping). But can I rely on that behavior across JVMs?
推荐答案
getClass
Object
的方法之一的运行时类:
code>派生。
So yes, it will always return Derived
.
这篇关于哪个类在基类的构造函数中getClass()报告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!