简体   繁体   中英

Type Mismatch Error when creating Object

When I created an object for subClass by Super Class as a reference Variable.
eg:

 class A {  
    A() { }  
 }  

 class B extends A {  
    B() { }  

    public static void main(String[] args) {  
       A a = new B(); // Compiles and runs
       B a = new A(); // Does not compile - "Type mismatch" error
    }  
 } 

If I have there A a = new B(); , it compiles and works. If I replace it with with B a = new A(); I get a "Type mismatch" error.

Why?

The reason is that the class B is more specific than the class A and the constructor for the class A creates only the stuff from class A .

Replace A with Animal and replace B with Baboon . Every baboon is an animal, but not every animal is a baboon . Now the following is perfectly OK:

Animal a = new Baboon();

And what you are trying to do is

Baboon a = new Animal();

So the compiler is unhappy, because your wife sent you to buy a baboon and you are bringing her a generic animal (maybe a basilisk?) :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM