-4

I'm trying to understand the following code and a little bit confused. After some Googling, I found Anonymus Classes In OOP. But can't understand why in this code they declared Sorting object and calling an instance of MergeSort with sorting = new MergeSort(); ? Can someone explain to me?

interface Sorting {
   List sort(List list);
}
class MergeSort implements Sorting {
    public List sort(List list) {
// sort implementation
        return list;
    }
}
class QuickSort implements Sorting {
    public List sort(List list) {
// sort implementation
        return list;
    }
}
class DynamicDataSet {
    Sorting sorting;
    public DynamicDataSet() {
        sorting = new MergeSort();
    }
// DynamicDataSet implementation
}
class SnapshotDataSet {
    Sorting sorting;
    public SnapshotDataSet() {
        sorting = new QuickSort();
    }
// SnapshotDataSet implementation
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
enginear
  • 29
  • 2
  • 9

2 Answers2

0

Because MergeSort is a Sorting implementation.

That whay you will only be able to use what the interface specifiebut it will be easier to change the implmentation you want to use. This is why it is a good practice to only handle interfaces.

See also this chapter of Oracles's doc.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35
0

In your code Sorting object is used to refer MergeSort() and QuickSort() because they have implemented Sorting interface. Interface directly can not be used to create a Object you can only use a reference of interface.

Lalit Verma
  • 782
  • 10
  • 25