本文介绍了方法重写和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Circle {

    public static final double PI = 3.141592654;
    protected double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public String toString() {
        return "Class = " + getClass().getSimpleName() + " (radius = " + radius + ")";
    }
}


public class PlaneCircle extends Circle {

    private double centerX, centerY;

    public PlaneCircle(double radius, double centerX, double centerY) {
        super(radius);
        this.centerX = centerX;
        this.centerY = centerY;
    }

    @Override
    public String toString() {
        return super.toString();
    }
}

假设上述两个类在不同的文件中。

Suppose the above two classes are in different files.

当我创建一个 PlaneCircle 的实例(在另一个java文件中),如下面两行...

When I create an instance of PlaneCircle (in another java file) like the following two lines...

PlaneCircle planeCircle1 = new PlaneCircle(3, 6, 7);
System.out.println(planeCircle1.toString());

我在控制台输出中得到的是

What I get in the Console output is

Class = PlaneCircle (radius = 3.0)

toString() PlaneCircle 中的方法调用 super.toString() ,当我使用时, Circle 中的 toString()方法应该给出Circle getClass()。getSimpleName()

The toString() method in PlaneCircle calls super.toString(), and the toString() method in Circle should give "Circle" when I use the getClass().getSimpleName().

我的问题是,为什么在这种情况下输出是PlaneCircle而不是Circle虽然我已经创建了子类的实例(PlaneCircle)?这与反射有什么关系吗?

My question is, why the output is "PlaneCircle" instead of "Circle" in this case even though I have created an instance of the subclass (PlaneCircle)? Does this have anything to do with reflection?

推荐答案

planeCircle1 是一个 PlaneCircle 的实例,这意味着 getClass()将返回 PlaneCircle.class (即代表 PlaneCircle 类的 Class 实例)和 getClass() .getSimpleName()将返回该类的名称 - PlaneCircle。

planeCircle1 is an instance of PlaneCircle, which means getClass() would return PlaneCircle.class (i.e. the Class instance that represents the PlaneCircle class) and getClass().getSimpleName() would return that class's name - "PlaneCircle".

从基类的方法调用 getClass()。getSimpleName()无关紧要 Circle ,因为当你调用没有实例变量的方法时,你在当前实例上调用它(即 getClass() this.getClass()相同,而的实例您的代码示例中的PlaneCircle

It doesn't matter that getClass().getSimpleName() is called from a method of the base class Circle, since when you call a method without an instance variable, you are calling it on the current instance (i.e. getClass() is the same as this.getClass(), and this is an instance of PlaneCircle in your code sample).

这篇关于方法重写和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 11:25