can someone please tell me why is it recommended to use interface as datatype ??
I’m trying to understand the best practices for designing robust and maintainable software systems in Java. One concept that I’ve come across is the recommendation to use interfaces as data types instead of base classes. However, I’m struggling to understand the reasoning behind this approach.
From my understanding, using an interface as a data type allows for more flexibility and polymorphism, as it enables me to work with any class that implements the interface. But I’m not convinced that this is the only reason, and I’d like to know more about the benefits of this approach.
Can someone explain why using interfaces as data types is preferred over using base classes? How does this approach improve code quality and respect the SOLID principles of object-oriented design?
I’ve tried to research this topic, but I’m still unclear about the advantages of using interfaces as data types. I’d appreciate any insights or examples that can help me understand this concept better.
>Solution :
One example below, either list1 or list2 can be used as an argument to the display method. If you explicitly used their class types, it wouldn’t work as you would need two method, one for ArrayList and one for LinkedList
This permits better maintenance of your code without having to make multiple changes should you choose a different implementation of some class, in this case ArrayList or LinkedList.
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new LinkedList<>();
public <T> T void display(List<T> list) {
System.out.printnln(list);
}
Although unrelated to your specific question, I used generics so List<String> list3 could also be an argument to display.
What follows is a more fun example. Note that I can assign each "animal" class to a list of MealTime since they each implement that interface. Otherwise those classes could only be assigned to a List<Object>.
interface MealTime {
public String feedMe();
}
class Lion implements MealTime {
private String food;
public Lion(String food) {
this.food = food;
}
public String feedMe() {
return food;
}
}
class Koala implements MealTime {
private String food;
public Koala(String food) {
this.food = food;
}
public String feedMe() {
return food;
}
}
public static void main(String[] args) {
List<MealTime> zoo = List.of(
new Koala("Eucalyptus leaves"),
new Lion("Eland meat"));
FeedTheAnimals(zoo);
}
public static void FeedTheAnimals(List<MealTime> zoo) {
for (MealTime animal : zoo) {
System.out.println("I am feeding the "
+ animal.getClass().getSimpleName() + " some " +
animal.feedMe());
}
}
prints
I am feeding the Koala some Eucalyptus leaves
I am feeding the Lion some Eland meat