为什么向上转换ab.a + ab.b会产生结果1和1.0? [英] Why upcasted ab.a + ab.b produce result 1 and 1.0?

查看:121
本文介绍了为什么向上转换ab.a + ab.b会产生结果1和1.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不知道如何在类A中没有参数的情况下调用构造函数. 在此特定示例中,向上转换如何工作?当我们生成A ab = bb;时,ab到底指的是什么?

I don't get how we managed to invoke constructor without parameters in class A at all. How upcasting works in this particular example? When we produce A ab = bb; what exactly ab refers to?

public class A {
    public Integer a;
    public Float b;

    public A() {
        a = 1;
        b = 1.0f;
    }

    public A(Integer x) {
        a = 2;
        b = 2.0f;
    }

    public int f(long x) {
        return 3;
    }

    public int f(double x) {
        return 4;
    }

}

public class B extends A {
    public int a;

    public B(float x) {
        a = 5;
    }

    public int f(int x) {
        return 6;
    }

    public int f(float x) {
        return 7;
    }

    public int f(double x) {
        return 8;
    }

}

public class M {
    public static void main(String[] args) {
        A aa = new A(1);
        System.out.println(aa.a + " " + aa.b);// OUT: [ 2 ] [2.0]

        int ret = aa.f(aa.b);
        System.out.println(ret); // OUT: [ 4 ]

        B bb = new B(6);
        A ab = bb;
        System.out.println(bb.a); // OUT: [ 5 ]
        System.out.println(ab.a + " " + ab.b);// OUT: [ 1 ] [1.0]

        ret = bb.f(1);
        System.out.println(ret); // OUT: [ 6 ]

        ret = ab.f(1.0f);
        System.out.println(ret); // OUT: [ 8 ]

        ret = ab.f(aa.a);
        System.out.println(ret); // OUT: [ 3 ]

        ret = bb.f(aa.b);
        System.out.println(ret); // OUT: [ 7 ]

    }
}

推荐答案

当我们生成A ab = bb;时,ab到底指的是什么?

When we produce A ab = bb; what exactly ab refers to?

它引用bb,但作为A,即只能调用A中定义的方法和属性.没有构造新对象.您可以通过选中System.out.println(bb == ab);来查看此情况,该结果将评估为true.这个概念称为属性或字段隐藏.

It references bb, but as an A, i.e. one can only call methods and attributes defined in A. There is no new object constructed. You can see this by checking System.out.println(bb == ab);, which will evaluate as true. This concept is known as attribute- or field-hiding.

这也是ab.a返回1的原因,因为访问了A中的属性a(类型为Integer).另一方面,如果一个人访问bb.a,则将在B中获得属性a(ob类型int),该属性被初始化为5.请记住,如果构造B,则始终会如

This also is the reason why ab.a returns 1, because the attribute a (of type Integer) within A is accessed. If one would, on the other hand, access bb.a, one would get the attribute a (ob type int) within B, which is initialzed to be 5. Keep in mind that, if you construct a B, there is always an explicit or implicit call to a superclass constructor as defined in JLS, §12.5.

这篇关于为什么向上转换ab.a + ab.b会产生结果1和1.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆