有趣代码二

来源:互联网 发布:外国人用淘宝吗 编辑:程序博客网 时间:2024/06/04 20:06

直接上代码:

import java.util.Date;public class Super_Keyword extends Date {public static void main(String[] args) {Super_Keyword sk = new Super_Keyword();sk.test();}public void test() {System.out.println(this.getClass().getName());System.out.println(super.getClass().getName());}}
输出结果如下:

Super_Keyword

Super_Keyword


这里也许一不注意,就认为输出结果是Super_Keyword和Date。

这个getClass()实在Object中定义的,其声明为了final native 。也就是说该方法是不能被子类覆盖的。所以this.getClass()与super.getClass()实际上都是调用的同一个方法,都是得到调用者的Class 对象。所以两行代码的输出都是 Super_Keyword。

如果想要得到父类的类名,需要使用this.getClass().getSuperClass().getName();

其实犯上面的错的原因就是不够仔细,被那个super给忽悠了。

原创粉丝点击