我目前正在尝试更好地了解继承。因此,我编写了一个简单的类来处理向量,然后想为2D向量创建一个类,该类继承自Vector类。这是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;
}
}
'''
<任何人都可以向我解释为什么会这样,我如何使它起作用?最好不要仅将方法复制到子类中。
谢谢
而不是声明新字段,而是在您的超类中将其声明为受保护的。
protected double[] coordinates;
您将可以在您的子类中为其分配:public Vector2d() {
this.coordinates = new double[2];
this.coordinates[0] = 0;
this.coordinates[1] = 0;
}
变量隐藏和变量隐藏与方法重写不同。
虽然变量隐藏看起来像覆盖变量(类似于方法覆盖),但不是。覆盖仅适用于方法,而隐藏则适用于变量。请参阅此链接以获取更多信息:variable-shadowing-and-hiding-in-java