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
Person person = new PersonImpl();
instead of
PersonImpl person = new PersonImpl();
The interface is supposed to be hiding the implementation?
Is this the correct way of using interfaces?
public class Driver {
public static void main(String [] args)
{
Person person = new PersonImpl();
person.setName("test name");
System.out.println("Name is "+person.getName());
}
}
public interface Person {
public void setName(String name);
public String getName();
}
public class PersonImpl implements Person{
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
This is the way to use interfaces.
The reason is so you could write another implementation later without changing code that uses
Person.So for now you can use
PersonImplbut later you might need aOtherTypeOfPersonImpl.You could create the new class implementing the same interface, and you could use the new class with any other code that expects a
Person.A good example is the
Listinterface.There are multiple implementations of
Listsuch asArrayList,LinkedList, etc. Each of these has advantages and disadvantages. By writing code that usesList, you can let each developer decide what type ofListworks best for them and be able to handle any of them without any changes.