-2

If we have class B that extends class A, and we have the following code:

A obj = new B();

Is obj variable refers to instance of A or B?

  • It is both but only the fields/methods of A are accessible. A doctor helps animals. He does not always care if it is a cat or a dog. While it is important to the specific treatment to know if it is a cat or a dog, it is fine to only know that it is an animal to make an appointment. Technically, the concrete instance is of the concrete type B. But as it inherits A this implies it is also an A. – Stuck Sep 13 '20 at 20:32

1 Answers1

0

Is obj variable refers to instance of A or B?

Both!

If you own a cat, do you own a cat or an animal? -- You can rightfully say you own both!

Paraphrased in code:

Animal a = new Cat();

a is a variable that holds a reference to a Cat object (which at the same time is an Animal object).

So...
...does a hold a reference to a Cat? Yes.
...does a hold a reference to an Animal? Yes.

aioobe
  • 413,195
  • 112
  • 811
  • 826