The interfaces in OOP paradigm used to generalized common behavior across group of somewhat similar objects. Therefore then you using variable of more general type, e.g. interface you will be able to use only those common methods which interface defines. Since you should be able to assign to interface variable any of interface descendants (classes which implements given interface) and be able to work with it. Therefore while you assign
Interface i = new Class();
the only methods you will be able to access is those defined in the Interface
. Additionally need to note, that variable will be dynamically binded to the runtime type, e.g. to the Class
in your example, thus the calls for methods defined in you interface will be dispatched to the implementation of the class.
Also think of the following, for example you have definitions:
interface Vehicle {
public void drive();
public void stop();
}
Now if you write code:
Vehicle v = new BMW()
v.drive()
// do something else
v.stop()
it should behave same when you replace new BMW()
with new Mitsubishi()
, regardless the fact that probably in your BMW
class you might have
class BMW {
public void listenMusic()
}
This is also called "Liskov substitution principle"
Liskov's notion of a behavioral subtype defines a notion of substitutability for objects; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.