Java polymorphism

2

In the context of inheritance, when B is subclass of A , an instance of B can be used anywhere where an instance of A is valid. This is the characteristic of polymorphism. However I have a question. I know it's correct:

A oa = new A();
B ob = new B();
A oab = new B();

However, is this also correct?

B oba = new A(); 

And if it is, I'd like to know why.

    
asked by anonymous 11.01.2018 / 20:01

2 answers

3

Think that B is Poodle and A is Cachorro . All Poodle is Cachorro , but the opposite is not always valid.

For example:

// Ok. Em uma variável do tipo Poodle, dá para colocar um Poodle sem problemas.
Poodle w = new Poodle();

// Ok. Poodle é um Cachorro, então dá para colocar em uma variável do tipo Cachorro.
Cachorro x = new Poodle();

// Ok. Cria algum vira-latas genérico e coloca em uma variável do tipo Cachorro.
Cachorro y = new Cachorro();

// Não! Não dá para se afirmar que um cachorro genérico é um poodle.
Poodle z = new Cachorro();
    
11.01.2018 / 20:50
5

Not correct because B is more specific than A . This would compile if you did a cast :

B oab = (B) new A ();

This is because although this is the new operator, an object coming from a variable of type A could have been created from a subclass C that was not compatible with B :

class C extends A{...}

A myA = new C ();
B myB = myA; // aqui precisa falhar a computação 

But if you put cast it's basically telling the compiler to trust you.

    
11.01.2018 / 20:14