【发布时间】:2020-06-14 09:58:51
【问题描述】:
我目前正在尝试更好地理解继承。因此,我编写了一个简单的类来处理向量,然后想为从 Vector 类继承的 2D 向量创建一个类。这是 Vector 类的代码:
'''
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 类:
'''
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 对象调用它,返回的字符串总是“()”,就好像坐标元组是空的一样。但是,当我将 toString() 方法添加到 Vector2d 类(使用复制和粘贴)时,它工作正常。
谁能向我解释为什么会这样以及如何让它发挥作用?最好不要只是将方法复制到子类中。
谢谢
【问题讨论】:
-
因为你覆盖了 Vector2d 中的坐标数组。您需要使用继承的值以及 getter 和 setter 来访问它,因为它是私有的。
-
这能回答你的问题吗? stackoverflow.com/questions/4716040/…
标签: java inheritance tostring