Interface versus concrete class

前端 未结 5 699
北荒
北荒 2021-02-05 12:06

Below I have a Person interface, an implementing class and a driver class which initialises the Person with a name and just outputs it again. What is the advantage of using

5条回答
  •  盖世英雄少女心
    2021-02-05 12:46

    what you did is correct. the advantage in using Person person = new PersonImpl() is that a loose coupling is maintained between the interface and the concrete implementation. PersonImpl person = new PersonImpl() is tightly coupled. and Person person = new Person() won't even compile.

    imagine you have a huge application, and a lot of code depends on the PersonImpl object. now suppose i want to change PersonImpl and make a new class, PersonImpl2. now i have to manually scan through the whole project and make changes everywhere. this might even break the code. this is called tight coupling, and is a bad thing. instead, if the rest of the code depended on a Person object, then even if i make a new PersonImpl2 class, things will work fine because PersonImpl2 implements Person.

提交回复
热议问题