【发布时间】:2023-01-08 03:02:03
【问题描述】:
public abstract class Vector{
public abstract double norm();
}
public class PlanarVector extends Vector {
protected final double x;
protected final double y;
public PlanarVector(double x, double y){
this.x=x;
this.y=y;
}
public double norm(){
return Math.sqrt(x*x+y*y);
}
public PlanarVector sum(PlanarVector v){
return new PlanarVector(x+v.x, y+v.y);
}
public String toString(){
return "x=" + x + " y=" + y;
}
}
public class SpaceVector extends PlanarVector {
protected final double z;
public SpaceVector(double x, double y,double z){
super(x,y);
this.z=z;
}
public double norm(){
return Math.sqrt(x*x + y*y + z*z);
}
public SpaceVector sum(SpaceVector v){
return new SpaceVector(x+v.x, y+v.y, z+v.z);
}
public String toString(){
return super.toString() + " z=" + z;
}
}
public class TestVector {
public static void main ( String[] args ) {
Vector v0 ;
PlanarVector v1 , v2 ;
SpaceVector v3 , v4 ;
v1 = new PlanarVector ( 3 , 4 ) ;
v0 = v1 ;
v2 = new SpaceVector ( 2 , 3 , 6 ) ;
v3 = new SpaceVector ( 2 , 1 , 0 ) ;
v4 = v3 ;
System.out.println(v1.sum(v2)) ; //expected output: x=5 y=7 realoutput: x=5 y=7 (v1 can only use PlanarVectorMethods because its dynamic and static type is PlanarVector)
System.out.println(v2.sum(v1)) ; //expected output: x=5 y=7 realoutput: x=5 y=7
System.out.println(v2.sum(v3)) ; //expected output: 'x=4 y=4 z=6' realoutput: 'x=4 y=4'
System.out.println(v3.sum(v2)) ; //expected output: 'x=4 y=4 z=6' realoutput: 'x=4 y=4'
System.out.println(v3.sum(v4)) ;
System.out.println(v1.norm()) ;
System.out.println(v2.norm()) ; //expected output: sqrt(13) realoutput: 7
}
}
有人能解释一下为什么“System.out.println(v2.sum(v3))”中的 v2.sum(v3) 不使用子类方法吗? 我知道 v2 的静态类型是 PlanarVector 但它的动态类型是 SpaceVector System.out.println(v3.sum(v2)) 也是如此,v3 的静态和动态类型是 SpaceVector,v2 在这里被认为是 planarVector?为什么?! 这次最后一个 System.out.println(v2.norm()) 将 v2 视为 SpaceVector ... 发生了什么?! 我还有最后一个问题,超类不能使用子类方法,即使它是子类的实例,对吗?如果该方法是子类中的重写方法会发生什么,为什么超类现在可以使用它(并使用子类实现)?
我在问一个关于 Java 基础知识的问题,希望通过示例获得简单明了的答案。
【问题讨论】:
-
“有人能解释一下为什么“System.out.println(v2.sum(v3))”中的 v2.sum(v3) 不使用子类方法”——因为子类方法不覆盖
sum,它过载它,因为参数类型不同。我强烈建议您在尝试覆盖方法时使用@Override注释 - 这样编译器可以在您实际上没有这样做时告诉您......
标签: java inheritance