ant2009
ant2009

Reputation: 22486

Using a interface type to instantiate a class object that implements the interface

Some confusion with using a interface as a type to instantiate a class object. Why do we need the interface as a type? When we can use the class instead? As the class implements the interface anyway. I know you cannot instantiate an interface.

Many thanks for any suggestions,

   public interface SortRecords {
        int query(int rowId);
    }

    public class OurPrice implements SortRecords {
        @Override
        public int query(int rowId) {
            return 0;
        }
    }

    public void test() {
        /* 
         * Why has the interface as the type? 
         */
        SortRecords sorterV1 = new OurPrice();
        sorterV1.query(1);

        /* 
         * Why not just do like this? 
         */
        OurPrice sorterV2 = new OurPrice();
        sorterV2.query(2);
    }

Upvotes: 0

Views: 61

Answers (2)

KDP
KDP

Reputation: 1481

basics of polymorphism.

read here http://www.artima.com/objectsandjava/webuscript/PolymorphismInterfaces1.html

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272217

The interface declares the contract, and provides you with the freedom to specify any other class providing the same contract. So the code referencing the interface is agnostic to the implementation you're providing.

In the above example, it's not particularly useful. However, in a wider context, a factory could provide you with any implementation it likes (even varying during runtime). As a consumer, you don't have to worry. You simply communicate using the interface and the contract (methods) it provides.

Upvotes: 5

Related Questions