-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
}
1
  • This question has been asked many times.. Commented Dec 3, 2017 at 12:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.