Java 继承铸造
我有两节课Java 继承铸造,java,inheritance,Java,Inheritance,我有两节课 class Vector{ ........ Vector(int x, int y, int z){...........} public Vector sum(Vector vc){ Vector result; ...........//all working and store to Vector result. return result; }
class Vector{
........
Vector(int x, int y, int z){...........}
public Vector sum(Vector vc){
Vector result;
...........//all working and store to Vector result.
return result;
}
public Vector subtract(Vector vc){................//codes}
}
class Velocity extends Vector{
Velocity(int x, int y, int z){......}
................
}
class Test{
public static void main(String args){
Velocity v1=new Velocity(14,14,14);
Velocity v2=new Velocity(14,14,14);
Vector result=v1.sum(v2); //here I want to get this result as Velocity
//I don't know how to get it....
}
}
以类似的方式,我有加速度,力,动量,位移类,它们扩展了向量类,它们都有相同的问题,除此之外
Vector result = ((Velocity)v1).sum(v2);
=========================================================
这不会有帮助,因为您在Vector中定义了sum
,返回Vector
。要生成结果
一个速度
,您需要一个返回类型速度
的求和方法,而不是向量
中返回向量的求和方法
更好的选择可能是提供一个Velocity
构造函数,该构造函数接受向量
Velocity result = new Velocity(v1.sum(v2));
Vector.java:
public interface Vector<T extends Vector> {
public int getX();
public int getY();
public int getZ();
public T sum(T other);
}
public abstract class BaseVector<T extends Vector> implements Vector<T> {
private final int x;
private final int y;
private final int z;
public BaseVector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
protected abstract T createNew(int x, int y, int z);
@Override
public T sum(T other) {
return createNew(x + other.getX(), y + other.getY(), other.getZ());
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public int getZ() {
return z;
}
@Override
public String toString() {
return "BaseVector [x=" + x + ", y=" + y + ", z=" + z + "]";
}
}
所有人都有同样的问题那是什么问题?你的结构不好;不要把速度看成是向量的延伸,把速度看成是向量所代表的东西。记住这一点,你可以简单地拥有一个vector类型的速度变量,或者如果你想实现某种维度分析,你可以使用泛型(在维度相关的类上参数化你的向量)no@Patricia Shanahan…我想要“result”变量作为速度。速度结果=v1.和(v2);我已经这样做了…但问题是我必须对其他类,如加速度、力、动量、扭矩等,做这件事…还有其他方法吗?如果你需要对多个矢量类做这件事,我想你需要类似EasterBunybugsMasher建议的解决方案。对于像Velocity这样的一个类来说更复杂,但是对于多个类来说代码更少。
public class Velocity extends BaseVector<Velocity> {
public Velocity(int x, int y, int z) {
super(x, y, z);
}
@Override
protected Velocity createNew(int x, int y, int z) {
return new Velocity(x, y, z);
}
}
public static void main(String[] args) {
Velocity v1 = new Velocity(14, 14, 14);
Velocity v2 = new Velocity(14, 14, 14);
Velocity result = v1.sum(v2);
System.out.println(result);
}
}