Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# Interface 2

Status
Not open for further replies.

Valeriya

MIS
Jan 9, 2006
138
US
Hi guys,
I'm new to C# sharp and wold like to ask a very general question. Could you please suggest a good article or maybe book that would have a very good (detailed explanation) of Interfaces and Inheritance. I'm having trouble grasping this subject.

Thanks,

Valeriya
 
I can give you a quick and simple explaination.

An interface is a definition of required properties, events, and methods that a class must implement in order to be used by another class that does not know the details of the implementing classes.

The simplest example of this is an Action classe. So our interface will define a single method called PerformAction:

public interface IMyActionClass
{
void PerformAction();
}

Now we will create a couple of classes that implement IMyActionClass:

public class StartCarClass : IMyActionClass
{
//this class implements IMyActionClass so it has PerformAction()

public StartCarClass()
{
}

public void PerformAction()
{
MessageBox.Show("Starting Car");
}
}

public class DriveCarClass : IMyActionClass
{
//this class implements IMyActionClass so it has PerformAction()

public DriveCarClass()
{
}

public void PerformAction()
{
MessageBox.Show("Driving The Car");
}
}


So now we have 2 classes that use IMyActionClass. So now we can use them by another class that knows nothing about either of these classes but only about the IMyActionClass interface.

public class ActionRunner
{
public ActionRunner()
{
}

public void RunSequence(IMyActionClass[] actions)
{
//This class is passed in a list of actions but it doesn't know anything about the StartCarClass or the DriveCarClass. It only knows to call PeformAction()

foreach(IMyActionClass action in actions)
{
//Run the event
action.PerformAction();
}
}
}


So who passes in the classes? Well this would come from another class in this case. We'll call it from our form class.

public class Form1 : System.Windows.Forms.Form //inherits the form class
{
public Form1()
{
InitializeComponent();

StartActionSequence(); //you might want to call this from a button press or something but this will cause the code to run when the form is created
}

public void StartActionSequence()
{
//Let's create our actions to run
IMyActionClass[] actions = new IMyActionClass[]{
new StartCarClass(), new DriveCarClass() }

//Let's now create an action runner
ActionRunner runner = new ActionRunner();

//Let's pass the actions to the runner and have the sequence begin
runner.RunSequence(actions);
}
}


And that's it. It allows a class to do work with other classes without knowing the full details of the class type.


Inheritance is a different issue. If you find this helpful let me know and I can write you something on inheritance too.
 
Short summary:

Interface: A contract which implementing classes must fulfill. It says "You must provide these methods for your callers"

Inheritance: Another word for this is specialization. You typically design an inheritance chain by going from the most generic to the most specific, such as Dachshund inherits from Dog, which inherits from Mammal, which inherits from Animal.

It's a good idea to get these concepts down, as they're frequently asked in job interviews.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Thanks Guys for a quick response!
JurkMonkey, your example was very helpful! And if you could, please do write me on the subject of Inheritance. Again thanks to both of you!!!

Valeriya
 
Chip is correct about going from most generic to most specific in most cases. So let's jump into an example.

Let's take a can of soda and a bottle of bleach. If you mix them together and drink them you will probably not be around to read the rest of this - so don't do that.

But a bottle and a can have something in common - they both contain a liquid. So the first thing we do is define our container object.

public class LiquidContainer
{
//Here we will define some generic properties that explain what a container is. These properties apply to both a Can and a Bottle.

public int SizeInML = 0;
public string ContainerMaterial = "";
public string Contents = "";


public LiquidContainer()
{
}
}

So we can say that a bottle of bleach and a can of soda has a size in millilitres, is made of some kind of material, and can hold some kind of contents.

So lets look a little further into the Bleach bottle - which will inherit the Container class.

public class BleachBottle : LiquidContainer //inherits from LiquidContainer by putting the class name after the :
{
//Any other class accessing this class can already see SizeInML, ContainerMaterial, and Contents so we don't have to add them here. We only add properties that are specific to the bleach bottle.

public int AcidityLevel = 7; //Default set to Neutral :)

public BleachBottle()
{
}
}

Wow that was simple (I think). So how do we use this class?

public class Form1 : System.Windows.Forms.Form //inherits from the Form class
{
public Form1()
{
InitializeComponent();
}

private BleachBottle CreateBleachBottle()
{
BleachBottle jaavex = new BleachBottle();

//Set the properties defined in LiquidContainer
jaavex.SizeInML = 710;
jaavex.ContainerMaterial = "Plastic";
jaavex.Contents = "Jaavex Bleach";

//Set the properties specific to BleachBottle
jaavex.AcidityLevel = 9;

return jaavex;
}

private void button1_Click(object sender, EventArgs e)
{
//A message box saying Jaavex Bleach" will show up
MessageBox.Show(CreateBleachBottle().Contents);
}
}


So now let's look at the can.

public class SodaCan : LiquidContainer
{
//This class will also have a specific property - LabelColor
public Color LabelColor = Color.Silver;

public SodaCan()
{
}

//We will also add a specific method to the can
public void OpenCan()
{
MessageBox.Show("pssssssssht"); //that's the can opening.... :)
}
}

So we can use this class.

public class Form1 : System.Windows.Forms.Form //inherits from the Form class
{
public Form1()
{
InitializeComponent();
}

private SodaCan CreateSoda()
{
SodaCan soda = new SodaCan();

soda.SizeInML = 355;
soda.ContainerMaterial = "Aluminum";
soda.Contents = "Dr. Pepperr";
soda.LabelColor = Color.DarkRed;

return soda;
}

private BleachBottle CreateBleachBottle()
{
BleachBottle jaavex = new BleachBottle();

//Set the properties defined in LiquidContainer
jaavex.SizeInML = 710;
jaavex.ContainerMaterial = "Plastic";
jaavex.Contents = "Jaavex Bleach";

//Set the properties specific to BleachBottle
jaavex.AcidityLevel = 9;

return jaavex;
}

private void button1_Click(object sender, EventArgs e)
{
//A message box saying Jaavex Bleach" will show up
MessageBox.Show(CreateBleachBottle().Contents);
}

private void button2_Click(object sender, EventArgs e)
{
//Open the can of soda
SodaCan soda = CreateSoda();

soda.OpenCan(); //use the method specific to SodaCan
}
}



You will notice above that the interface typically follows the : in the class declaration and so does a class type that we are inheriting from (often called a base class)

so how do we use an interface and a base class?

public class JuiceBox : LiquidContainer, IMyActionClass
{
public JuiceBox()
{
}

public void PerformAction()
{
MessageBox.Show("Squeeeeeeze and out comes the juice!");
}
}


So we can use this class by creating the JuiceBox as a container and runnind the action on it.

public void DoSomething()
{
JuiceBox juice = new JuiceBox();

juice.SizeInML = 160;
juice.ContainerMaterial = "Cardboard";
juice.Contents = "Fruit Punch";

StartActionSequence(juice);
//we can pass in the JuiceBox class because it implements the IMyActionClass interface.
}

public void StartActionSequence(IMyActionClass action)
{
//Even though we are passed in a juice box we cannot access the properties of LiquidContainer or of JuiceBox specifically because this method only knows the JuiceBox as a IMyActionClass which only contains the method PerformAction();

action.PeformAction();
}


I hope that makes some sense. If you have more questions let me know.
 
The signature of a method is given by its return type and the types of its parameters.

For example the method Int32 Compute( Int32 a, Int32 b) has the signature Int32(Int32, Int32).


An interface is the sum of all the signatures of a class.

Here the expression the sum of all signatures means the collection of.


When it comes to inheritance... is just as in real life. Think about it that way: Parents have some genetic markers, which the child will inherit. That means that the child will share the same characteristics with its parent(s).

Now, the genetic markers are the members of the parent class (methods, attributes). The child class will inherit from its parent these markers. Unlike the real life, a child can have one or more parents (in C# more parents means that maximum one is a class, all others are interfaces).
 
JurkMonkey, those were to very clear and succinct answers.

A star for you for sure.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
*Two, not to. I'm obviously not on my game this morning.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top