Interface

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

hi
My question might be a simple questions. I am doing C# maintanance project
I have seen so many places Interface is used in my main class. But I could't not understan
what is the use of Interface. Because Interface having only the Property and method
declaration only. Why we have to use that instead of writing directly in the main class?

1. What is the advatage of use of Interface (or disadvantage) instead of writing property and
method directly

2. When we have to use Abstract class and when we have to use Interface

Is there is any site which is explaining about the difference and usage?? Please let me kno

thank
Kanna
 
You'd write an interface when you want to use the interface as a data type -
and have many classes that you could use.. for example (interfaces always
have an "I" in the front):

IDataAccess objMyObject;

objMyObject = new OfflineAccess();
objMyObject = new DirectAccess();
objMyObject = new WebSvcAccess();

Assuming that OfflineAccess, DirectAccess and WebSvcAccess all "implemented"
that IDataAccess interface - you could instantiate that object with any of
them..


And you use an interface when you want to define JUST the interface (what
methods and properties a class should have) - and you implement an abstract
class when yuo want to do that, and include some base logic or default
functionality of those methods or properties.

HTH
 
Client code can refer to objects which implement an interface through an
interface variable. Eg, if two classes implement IPersist, some client code
can use instances of both classes through an IPersist-typed variable.

An abstract class can be partially implemented, ie, it can have both
abstract members AND implemented members. An interface is functionally akin
to an abstract base class with ONLY abstract members.

Brad Williams
 
You will need to read a little about Object oriented programming...
Essential what does it mean when we say Interface means we are
specifying a "contract" is the following...

Going back to OOPS 101

Consider Animal as an Interface (read as Animal exhitbits certain
behavior i.e breathing)
Now Man is characterized by this animal behaviour of breathing ( read as
implements interface) Take a different Animal, Fish, it implements the
same behaviour but differently!

So what has the Interface achieved, extracting some common behaviour
"contract" from the different animals

Now if you think certain behaviour can be similarly exhibited you'd use
the abstract class. For example you could say Apes are an classification
(read as abstract) of Animals which breath with lungs. So if you're
dealing with different apes then you would use the behaviour described
by Apes.

Hope that clarifies things




So
 
Back
Top