继承重写的 toString 方法不使用正确的属性

inherited overridden toString method does not use the proper attributes

我目前正在努力更好地理解继承。因此,我写了一个简单的 class 来处理向量,然后想为继承自 Vector class 的 2D 向量创建一个 class。这是 Vector class:

的代码

'''

    public class Vector {

private double[] coordinates;

public Vector() {
    this.coordinates = new double[0];
}

public Vector(int dim) {
    this.coordinates = new double[dim];
    for(int i=0;i<dim;i++) this.coordinates[i] = 0;
}

public Vector(double[] values) {
    this.coordinates = new double[values.length];
    for(int i=0;i<values.length;i++) this.coordinates[i]=values[i];
}

public void set(double[] values) {
    for(int i=0;i<Math.min(this.coordinates.length, values.length);i++) this.coordinates[i]=values[i];
}

public double[] get() {
    return this.coordinates;
}

public double norm() {
    double sqSum =0;
    for(double i:this.coordinates) sqSum += i*i;
    return Math.sqrt(sqSum);
}

public int getDim() {
    return this.coordinates.length;
}

public double skalarprodukt(Vector other) {
    if(this.getDim()!=other.getDim()) return Double.NaN;
    double sp = 0;
    for(int i=0;i<this.getDim();i++) sp += this.coordinates[i]*other.coordinates[i];
    return sp;
}

public boolean isOrthogonal(Vector other) {
    if(Math.abs(this.skalarprodukt(other))<0.000001) return true;
    return false;
}

public void add(Vector other) {
    if(this.getDim()== other.getDim()) {
        for(int i=0;i<this.getDim();i++) this.coordinates[i] += other.coordinates[i];
    }
}

@Override 
public String toString() {
    String ret = "(";
    for(int i=0; i<this.coordinates.length;i++) {
        ret += this.coordinates[i];
        if(i<this.coordinates.length-1) ret+=", ";
    }
    ret+=")";
    return ret;
}

    }

'''

这里是 Vector2d class:

'''

    public class Vector2d extends Vector {

private double[] coordinates = new double[2];


public Vector2d() {
    this.coordinates[0] = 0;
    this.coordinates[1] = 0;
}

public Vector2d(double x, double y) {
    this.coordinates[0] = x;
    this.coordinates[1] = y;
}

    }

'''

现在,如果我为 Vector 对象调用 toString 方法,它会执行它应该执行的操作(即 Vector (1,1) 显示为 "(1,1)" ),但如果我为一个对象调用它Vector2d 对象,返回的 String 始终为“()”,就好像坐标元组为空一样。但是,当我将 toString() 方法添加到 Vector2d class(通过复制和粘贴)时,它工作正常。

任何人都可以向我解释为什么会这样以及如何让它发挥作用吗?最好不要将方法复制到 subclass.

谢谢

Vector2d 和 Vector 中的私有字段是独立的。它们仅在声明它们的 class 中可见。

与其声明新字段,不如在您的 superclass 中将其声明为受保护:

protected double[] coordinates;

然后您将能够在您的子class:

中分配给它
public Vector2d() {
    this.coordinates = new double[2];
    this.coordinates[0] = 0;
    this.coordinates[1] = 0;
}

您正在做的事情叫做变量隐藏变量隐藏与方法覆盖不同

虽然变量隐藏看起来像覆盖变量(类似于方法覆盖),但它不是。覆盖只适用于方法,隐藏适用于变量。

有关详细信息,请参阅此 link:

overriding-vs-hiding-java-confused