有 Java 编程相关的问题?

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

强制转换Java对象分配转换

在下面的例子中,我不明白为什么Base b1 = new Derived(); System.out.println(b1);打印出x=10, z=20。我的理解是,因为b1有一个静态类型的Base,它不能访问Derived中的字段,所以z不应该被打印出来。谁能帮我解释一下吗?非常感谢

class Base {
  int x;
  public Base1() { x = 10; }
  public Base1(int x) { this.x =x; }
  public String toString() {
     return "x=" + x ;
  } 
 }
 class Derived1 extends Base1 {
     int z = x * 2;
     public Derived1() {}
     public Derived1(int x, int z) {
        super(x);
        this.z = this.z + z;
     }
     public String toString() {
        return "x=" + x + ", z=" + z;
     }
  }

共 (2) 个答案

  1. # 1 楼答案

    直接从http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

    A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members

    在代码中,您调用默认构造函数来创建一个新的Derived1对象:
    Base b1 = new Derived();,这反过来又调用您碰巧设置x = 10的父类的默认构造函数。在那之后,你进入这一行int z = x * 2;

  2. # 2 楼答案

    对象Derived,而不是Base。从b1到对象的接口BaseBasetoString,所以你可以访问toString。您访问的实现是对象拥有的实现,它由使用Derivedz提供。Derived#toString的实现可以访问z,因为它对对象的引用是通过Derived引用(this)而不是Base引用进行的

    正如奥利在一篇评论中指出的,这是多态性的基础——让对象的行为取决于对象,而不是对象的接口

    如果对象的内部是由我们与它的接口决定的,那么我们在实现interfaces!时会遇到相当大的麻烦:-)