whether the results are the same of getClass().getName() called in child class and parent class?
UsageGetClass2.java
abstract class AbstractClass {
public AbstractClass() {
System.out.println("the current class(in AbstractClass):" + this.getClass().getName());
}
abstract public void print();
}
public class UsageGetClass2 extends AbstractClass {
public UsageGetClass2() {
super();
}
public static void main(String[] args) {
UsageGetClass2 g = new UsageGetClass2();
g.print();
System.out.println("the current class is(in child class): " + g.getClass().getName());
}
public void print() {
System.out.println("hello world!");
}
}
the result:
xxx:~/java/getclass$ java UsageGetClass2
the current class(in AbstractClass):UsageGetClass2
hello world!
the current class is(in child class): UsageGetClass2
the results are the same.
本文通过一个具体的Java示例展示了getClass().getName()方法在父类和子类中的使用情况,并验证了该方法返回的类名是否一致。实验结果显示,无论是在父类还是子类中调用,返回的都是子类的全限定名。

被折叠的 条评论
为什么被折叠?



