有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将继承类的对象分配给超类对象

我有两个给定的课程A和B。 B继承自A

现在在M类的主方法中有一个 指向B的一个对象

我知道,如果一个继承类的对象被分配给一个超类,那么子类的方法就会保留

问题:那么为什么B的z.(-6)方法f(double y)被使用而不是f(int y)? 或者换句话说:你能解释为什么输出为-8.0和4.0吗

public class A {
   public int x = 2;

   public A() {
      this.x+++;
   }

   public A(int x) {
      this.x += x;
   }

   public void f(double x) {
      this.x = (int) (x + B.y);
   }
}


public class B extends A {
   public static double y = 3;

   public double x = 0;

   public B(double x) {
      y++;
   }

   public void f(int y) {
      this.x = y * 2;
      B.y = 0;
   }

   public void f(double y) {
      this.x = 2 * y + B.y;
   }
}


public class M {
   public static void main(String[] args) {
   A a = new A((int) B.y);
   System.out.println(a.x); // OUT: [5]

   B b = new B(2);
   System.out.println(b.x + " " + B.y); // OUT: [0.0] [4.0]

   A z = b;
   System.out.println(z.x); // OUT: [3]

   z.f(-0.5);
   System.out.println(b.x + " " + z.x); // OUT: [-6.0] [3]

   z.f(-6);
   System.out.println(b.x + " " + B.y); // OUT: [-8.0] [4.0] 
   }
}

共 (1) 个答案

  1. # 1 楼答案

    在您的示例中z引用而不是对象z指向B实例,不管编译器是否知道它

    So why is for z.(-6) the method f(double y) of B used and not f(int y)?

    您已经告诉编译器z是对A的引用,并且它只有一个方法f(double),可以被重写,但不能被子类重载

    也就是说,被调用方法的签名是在编译时(编译器的类型)而不是运行时(不是实际类型)确定的