Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Interface and not a just regular classes

Tags:

oop

interface

It's a newbie question.

I understand the technical implementation of Interfaces, Abstract classes etc. and I do understand the programmatic differences and how and when to use them. I understand that an interface is like a forced contract without a concrete definition which all implementing classes must implement but I fail to understand why such a contract should be forced in the first place?

For instance, I've a hotel 'H' that has some rooms that can be reserved,

interface H{
//example method to implement  
reserveRoom(int n, ...) {}

... other methods
}

on the other hand I've travel booking sites A1, A2, A3 etc which might have their own discount/commission programs, which might up-sell/down-sell to their guests but what I don't get is what does it might have to do with Hotel 'H' booking policy. As the only thing Hotel H is interested in getting a room filled at their asking price.

Please explain why the need of such a design of using interfaces?

Thanks.

like image 672
avi Avatar asked Aug 30 '26 08:08

avi


1 Answers

Consider interface like a rule-set for your implementations. If you follow the rule-set you can guarantee that consumers will be able to shift to your implementations seamlessly.

Just like JDBC interfaces for example. Java has provided set of interfaces as JDBC and the DB vendors do provide implementations for those interfaces.

That is why your statement like below, stands valid irrespective of which database you are connecting to.

Statement stmt = conn.createStatement( )

Consider, there were no interfaces (JDBC) and MySql driver changed the createStatement() to makeStatement(). You will have to change the code and you will end up writing Database specific code

like image 65
Amit Phaltankar Avatar answered Sep 04 '26 00:09

Amit Phaltankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!