C# Crawler
Sagiv Hadaya is crawling in C#...just for fun




 

C# Abstract Classes

Suppose you are implementing a new class that you want others to derive from. lets say...Car, the abstract class might look something like this:

public abstract class Car

{

      public abstract void RemoveAllFuses();

      public abstract void StartEngine();

}

as you see, abstract class has methods that are NOT implemented, but just declared, the deriving class should implement them.

The Car exaple here state an abstract Car, and its exactly what it is, abstract, a car with no name and no functionality yet, but with some declaration on what it does (of course regular car has more than StartEngine and RemoveAllFuses).

now each car who derive from the abstract one must implement both methods.

for example:

class Seat : Car

{

         public override void RemoveAllFuses()

         {

         }

         public override void StartEngine()

        {

         }

}

 

thats great...but now the question:

What should you do in order NOT to let a certain method withing the derived to be called?

eg, what whould you do to prevent this:

 

class MyCar : Seat

{

     static void Main(string[] args)

     {

          MyCar c= new MyCar();

          try

          {

           c.RemoveAllFuses();

           }

           catch (Exception e)

           {

            System.Console.WriteLine(e.Message);

             }

   }

}

you ask why? well, i say, Seat Car maker did not want to implement RemoveAllFuses.

the answer is really in the code, in the try block.

in the Seat Class, we should throw an exception in order to make that method unavailable, and at the same time, we have actually implemented it. this is what you do if you DONT NEED ALL METHODS from a derived class.

the modifed Seat class is:

class Seat : Car

{

         public override void RemoveAllFuses()

         {

                 throw new MethodAccessException();

         }

         public override void StartEngine()

        {

         }

}

 

MethodAccessException is being explained as "Attempt to access the method failed"...as simple as that.


Click here to visit the Radio UserLand website.
Click to see the XML version of this web page.
Click here to send an email to the editor of this weblog.
© Copyright 2002 Sagiv Hadaya.
Last update: 10/11/2002; 2:19:55 AM.