"Raja Chandrasekaran" <Ra*****@gmail.com> a écrit dans le message de news:
11**********************@j55g2000cwa.googlegroups. com...
| I really wonder, If the interface does not have any
| definition, Y do we need to use interface. You can then only we can use
| Multiple inheritance. I really cant understand, Just for declararion y
| do we need to use interface. Anyhow the method name and definition ll
| be in the derived class. Instead of that we can do all code in the
| derived class itself right...? Then y these concept came. If anybody
| know, please explain me with an example has right situation...
The quick answer is that an interface is a contract that can be implemented
in a class.
You mention multiple inheritance; yes, one interface can inherit from more
than one other interface, but classes do not inherit from interfaces, they
implement them.
The difference between an interface and a class is that an interface is
purely a contractual definition that has no implementation at all. It is
similar to a pure abstract class, except that an abstract class can also
contain state fields and base behaviour.
Interfaces are intended to define the what without defining the how.
If you inherit from one class into another, then the derived class "is" also
the base class.
But because you can never derive from more than one base class at a time,
the ability to implement more than one interface gives people the impression
that interfaces provide multiple inheritance.
Another difference between an interface and a base class is that a base
class has to be the root of a hierarchy, vertical inheritance; whereas an
interface can be implemented across multiple hierarchies, a sort of
horizontal "inheritance"
A simple example of the differences is :
class Vehicle
{
}
class Car : Vehicle
{
}
interface ISteerable
{
void Steer();
}
class Car : Vehicle, ISteerable
{
void Steer()
{
// change direction of wheels
}
}
abstract class Boat : ISteerable
{
abstract void Steer();
}
class Speedboat : Boat
{
override void Steer()
{
// turn outboard motor
}
}
class Ship : Boat
{
override void Steer()
{
// turn rudder
}
}
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer