在下面的 java 代码中,这是实现向上转型和向下转型的正确方法吗?

Is this the correct way to implement upcasting and downcasting in the following java code?

package test;
public class Test {

     public static void main(String[] args) {
        A a2 = new B();               // 1
        a2.display1(); 
        a2.display();
        ((B) a2).display2();          //  2
        ((A) a2).display();           //  3
        B b1 = new B();
        b1.display1();                //  4
     }
}

class A {
    int a = 10;

    void display() {
        System.out.println("parent class " + a);
    }

    void display1() {
        System.out.println("parent class " + (a + 10));
    }
}

class B extends A {
    int a = 30;

    @Override
    void display() {  
        System.out.println("child class " + a);
    }

    void display2() {
        System.out.println("child class " + (a + 10));
    }
}
  1. 创建了谁的对象?class A 或 B。
  2. 这是垂头丧气吗
  3. 为什么这不是调用classA的方法?如何使用此对象而不是 A.
  4. 的对象调用 class A 的方法(覆盖一个)
  5. 这是隐含的向上转换吗?
  6. 如果 class A 有一个嵌套的 Class B 而不是 class A 的对象创建期间 class b 的对象是否也形成了?我无法从 A
  7. 的对象使用 class B 的方法
  1. 你做了 new B(),所以显然创建了一个 B 对象。

  2. 是的,从类型 AB 的子类型 class 层次结构。

  3. 因为a2引用了一个B对象,调用哪个方法是通过查看对象的类型动态决定的(在运行时,而不是在编译时)实际对象是。

  4. 不,这里根本没有演员表。

  5. 我不太明白你的意思。变量的类型决定了你可以调用哪些方法,但实际调用哪个方法取决于变量所引用的对象的实际类型。