Home>

I'm not sure why the Java upcast will do the type conversion automatically.
I also don't know if the downcast has to be explicitly cast.

nothing special

Applicable source code
class A {
    void dispA() {
        System.out.println("A");
    }
}
class B extends A {
    void dispB() {
        System.out.println("B");
    }
}
class Test {
    public static void main(String[] args) {
        B b = new B();
        A a = b;
        a.dispA();
    }
}
What I tried

nothing special

Supplementary information (FW/tool ​​version, etc.)

Tool used: eclipse4_8.0

In type conversion of basic data (primitive) type, when substituting a small type for a large type, type conversion is automatically performed,
I learned that when assigning a large type to a small type, you have to cast explicitly.

In the above source code, it looks like subclass .b (large type) is assigned to superclass .a (small type).
On the contrary, I don't understand the reason why the type conversion must be done explicitly when subclass .a (large type) is assigned to superclass .a (small type).

Is it handled differently than when assigning basic data (primitive) types?

It didn't come out even if I searched on the Internet because there was no one stumbled here.
Could you teach me

  • Answer # 1

    Because subclass is created by adding fields and methods to superclass,
    It is a class that has more information and can do compared to the super class.
    Turn it over,Only subclass types that have stricter restrictions than superclass can be put,It means that. In this sense, subclasses are "smaller" types than superclasses.

  • Answer # 2

    It looks like you're assigning subclass .b (large type) to superclass .a (small type)

    House,What can be putFrom that point of view, the super class is the "bigger type".