Java polymorphism

Asked

Viewed 197 times

2

In the context of inheritance, when B is sub-class of A, an instance of B can be used anywhere where an A is valid. This is the characteristic of polymorphism. However I have a question. I know it’s right:

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

However, this is also correct?

B oba = new A(); 

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

2 answers

5

It’s not right because B is more specific than A. That would compile if you made one cast:

B oab = (B) new A ();

That’s because, although here is the operator new, an object that came from a variable of type A could have been created from a subclass C which is 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 the cast basically you’re telling the compiler to trust you.

3


Think that B is Poodle and A is Cachorro. All Poodle is a 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();
  • Thank you! I get it :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.