在Java中,super.getClass()打印" Child"不是“父母” - 这是为什么? [英] In Java super.getClass() prints "Child" not "Parent" - why is that?

查看:94
本文介绍了在Java中,super.getClass()打印" Child"不是“父母” - 这是为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java类和对象中,我们使用this关键字来引用类中的当前对象。
从某种意义上说,我相信这个实际上会返回它自己的对象。

In Java classes and objects, we use "this" keyword to reference to the current object within the class. In some sense, I believe "this" actually returns the object of itself.

示例:

class Lion
{
    public void Test()
    {
        System.out.println(this);  //prints itself (A Lion object)
    }
}






在超类和子类的场景中。我认为超级关键字会返回超类的对象。但是这次我似乎弄错了:


In the scenario of a superclass and subclass. I thought that "super" keyword would return the object of the superclass. However it seems that I got it wrong this time:

示例:

class Parent
{
    public Parent(){
    }
}

class Child extends Parent
{
    public Child(){
        System.out.println(super.getClass()); //returns Child. Why?
    }
}

我的问题:在上面的例子,我期望编译器打印出 class Parent ,但它打印出 class Child 。为什么会这样?超级实际返回的是什么?

My Quesiton: In the above example, I was expecting the compiler to print out class Parent, however it prints out class Child. Why is this so? What super actually returns?

推荐答案

使用 super 的方法调用只是忽略当前类中的任何覆盖。例如:

A method call using super just ignores any overrides in the current class. For example:

class Parent {
    @Override public String toString() {
        return "Parent";
    }
}

class Child extends Parent {
    @Override public String toString() {
        return "Child";
    }

    public void callToString() {
        System.out.println(toString()); // "Child"
        System.out.println(super.toString()); // "Parent"
    }
}

如果是电话到 getClass(),这是一个方法,它返回它被调用的类,并且不能被覆盖 - 所以虽然我可以看到为什么你可能期望它返回 Parent.class ,它仍然正常使用相同的实现,返回 Child 。 (如果你真的想要父类,你应该看看 Class API。)

In the case of a call to getClass(), that's a method which returns the class it's called on, and can't be overridden - so while I can see why you'd possibly expect it to return Parent.class, it's still using the same implementation as normal, returning Child. (If you actually want the parent class, you should look at the Class API.)

这是经常使用的事实上,作为覆盖的一部分。例如:

This is often used as part of an override, in fact. For example:

@Override public void validate() {
    // Allow the parent class to validate first...
    super.validate();
    // ... then perform child-specific validation
    if (someChildField == 0) {
        throw new SomeValidationException("...");
    }
}

这篇关于在Java中,super.getClass()打印" Child"不是“父母” - 这是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆