public class Test { public static void main(String[] args){ A a = new B(); // *** } } class A { ... } class B extends A { ... } 

who can explain the pros and cons of the highlighted line, i.e. why is A a = new B() done, and when is it better A a = new А() or В a = new B() , well, or В a = new B() ?

  • one
    In this case, this line has no pros and cons. In each case there may be pros and cons. - KoVadim
  • one
    Well, that's what I ask, i.e. I wonder when I should use each of the options? where who inherits whom? - Gorets
  • one
    B inherits A. And here is where you need to use - ... Well, for example, you can create a Map <Integer, A>. In this case, it will be possible to push objects B into this map, but not vice versa. - KoVadim

1 answer 1

The question, A a = new B() or B a = new B() specifically solved in this case simply.

If for future use only the interface that is provided by the class A is enough for you, then it is always better to use A a = new B() . This reduces coupling ( coupling ) of objects, since all further code operates only on an interface provided by class A

Especially since in such a case, you can easily write a C extends A class C extends A and easily replace the entry with A a = new C() , which is, of course, good.

In modern IDE quite often you can find auto-factoring like Use Base Type where possible , which automates such scenarios.


The problem becomes much more interesting in the case of interfaces and work at the interface level. In many cases, it is possible to declare an anonymous object , which impersonates an interface in its own special way and, for example, passes it to a function that operates on objects that implement this very interface.

For more details and examples of code, see here and, for example, (at a more industrial level) in Effective Java.


Further, by the way, this all evolves into conversations about IoC , Dependency Injection and other code decoupling techniques.

The main principle is to reduce dependencies and code contact points, work through interfaces and select the required object with some interface depending on the settings of the injection module / IoC контейнера .