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;
}
}
Concrete methods in an interface All the methods in an interface must be abstract, you cannot have a concrete method (the one which has body) if you try to do so, it gives you a compile time error saying “interface abstract methods cannot have body”.
Using references to interfaces instead of their concrete implementation classes helps in minimizing ripple effects, as the user of an interface reference doesn't have to worry about the changes in the underlying concrete implementation.
An abstract class is a class declared with an abstract keyword which is a collection of abstract and non-abstract methods while a concrete class is a class that allows creating an instance or an object using the new keyword. Thus, this is the main difference between abstract class and concrete class.
An abstract class cannot be directly instantiated using the new keyword. A concrete class can be directly instantiated using the new keyword. An abstract class may or may not contain abstract methods. A concrete class cannot contain an abstract method.
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 PersonImpl
but later you might need a OtherTypeOfPersonImpl
.
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 List
interface.
There are multiple implementations of List
such as ArrayList
, LinkedList
, etc. Each of these has advantages and disadvantages. By writing code that uses List
, you can let each developer decide what type of List
works best for them and be able to handle any of them without any changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With