Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. When to use & when not to use ( Abstract Class & Interface )

When to use & when not to use ( Abstract Class & Interface )

Scheduled Pinned Locked Moved C#
designtutorial
20 Posts 7 Posters 4 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Keith Barrow

    Sorry to steal Pete's thunder. You can't use an interface for the implementation of common functionality, all an interface does is define what is available not how it is actually achieved. Lets take a simple example, modelling a cats which can for simplicity only look around or make a noise the Interface would look like:

    public interface IFeline
    {
    LookAround();
    MakeNoise();
    }

    OK, lets say I want to model a Tiger and a Cat. Both Implement IFeline, both look around in the same way, but a cat purrs but a Tiger roars. LookAround is common to both and should be in a base class. I don't ever want to create and instance of the base class, so I create an abstract one which encapsulate what is common:

    public abstract class Feline: IFeline
    {
    public LookAround()
    {
    Console.WriteLine("Looking");
    }

    public abstract MakeNoise(); //This is needed to stop the compiler complaing
    

    }

    Now I can implement the differing functionality:

    public class Cat: Feline
    {
    public MakeNoise()
    {
    Console.WriteLine("Purrr");
    }
    }

    public class Tiger: Feline
    {
    public MakeNoise()
    {
    Console.WriteLine("Roar");
    }
    }

    Hope this helps!

    Sort of a cross between Lawrence of Arabia and Dilbert.[^]
    -Or-
    A Dead ringer for Kate Winslett[^]

    K Offline
    K Offline
    Krishna Varadharajan
    wrote on last edited by
    #8

    Hi, Mr.Keith I really love you, such a sweet example which opens my eyes. I clear about the abstract class now. But, why I should't use like below code ?? public class Cat: Ifeline { public MakeNoise() { Console.WriteLine("Purrr"); } public LookAround() { Console.WriteLine("Looking"); } } public class Tiger: Ifeline { public MakeNoise() { Console.WriteLine("Roar"); } public LookAround() { Console.WriteLine("Looking"); } } krishna

    K 1 Reply Last reply
    0
    • K Krishna Varadharajan

      Hi, I know the functionality of Abstract Class & Interface. But, in which situation i can use this. Consider I am starting a new project and I need to design and create a class. So here in which situation I should create AbstractClass or Interface. How to find out which is suitable for particular situation. Please give me some practical situation where I can use and where I can't. krishna

      P Offline
      P Offline
      PIEBALDconsult
      wrote on last edited by
      #9

      Let it evolve as you develop it. Don't force it.

      1 Reply Last reply
      0
      • G GuyThiebaut

        You are correct, although I am not Mr Christopher I am Mr Guy ;) The interface declares the methods you will be implementing such as print, add line, page header, page footer etc. The abstract class then implements these methods but cannot be instantiated - so you then create classes that use the abstract class as their base class overriding the add line etc methods. Does that make sense to you?

        “That which can be asserted without evidence, can be dismissed without evidence.”

        ― Christopher Hitchens

        K Offline
        K Offline
        Krishna Varadharajan
        wrote on last edited by
        #10

        Mr. Guy, I am very much clear about what you said. Now I have another doubt, Is that any rules that abstract class must inherit interface, than we need to override from abstract class ? I can create a normal class which can implement this Interface and use those methods. But here we have to create instance of the class to access those implemented methods. So overall you mean to say that, one of the reason to go for abstract class to avoid creating instance of the class ? krishna

        G 1 Reply Last reply
        0
        • K Krishna Varadharajan

          Hi, I know the functionality of Abstract Class & Interface. But, in which situation i can use this. Consider I am starting a new project and I need to design and create a class. So here in which situation I should create AbstractClass or Interface. How to find out which is suitable for particular situation. Please give me some practical situation where I can use and where I can't. krishna

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #11

          Abstract class and inheritance is all about building a hierarchy (or family) of classes while Interface is to enforce a contract. Consider this hierarchy of classes. You can create FlyingVehicle as an abstract class.

          Vehicle --> FlyingVehicle --> Helicopter

          Consider another hierarchy of classes. You can create Bird as an abstract class.

          Animal --> Bird --> Eagle

          While the two families of classes are distinct, both the the FlyingVehicle and the Bird classes can implement an Interface called IFlyable.

          interface IFlyable {
          void Fly();
          void Land();
          }

          As you can see in this example, you created two distinct families of classes using Abstract classes and enforced the ability to fly using an interface.

          K 1 Reply Last reply
          0
          • K Krishna Varadharajan

            Mr. Guy, I am very much clear about what you said. Now I have another doubt, Is that any rules that abstract class must inherit interface, than we need to override from abstract class ? I can create a normal class which can implement this Interface and use those methods. But here we have to create instance of the class to access those implemented methods. So overall you mean to say that, one of the reason to go for abstract class to avoid creating instance of the class ? krishna

            G Offline
            G Offline
            GuyThiebaut
            wrote on last edited by
            #12

            Hi Krishna, Please just call me Guy as Mr Guy is too formal for the codeproject ;) An abstract class does not need to implement an interface. An abstract class must be inherited as you cannot create an instance of an abstract class - think of an abstract class as something like a Feline, in Keith's excellent illustration, which is a concept and for which there is no such concrete existence. However there are tigers which are Feline and are very much concrete - so a tiger inherits from the abstract class of Feline. You can just create an abstract class and then inherit from that class to create your instances(without implementing an interface). An abstract class allows you to implement some very general methods such as the LookAround method in Keith's illustration which will not need to be overridden. Abstract classes are a means of writing less code and implementing polymorphism.

            “That which can be asserted without evidence, can be dismissed without evidence.”

            ― Christopher Hitchens

            K 1 Reply Last reply
            0
            • K Krishna Varadharajan

              Hi, Mr.Keith I really love you, such a sweet example which opens my eyes. I clear about the abstract class now. But, why I should't use like below code ?? public class Cat: Ifeline { public MakeNoise() { Console.WriteLine("Purrr"); } public LookAround() { Console.WriteLine("Looking"); } } public class Tiger: Ifeline { public MakeNoise() { Console.WriteLine("Roar"); } public LookAround() { Console.WriteLine("Looking"); } } krishna

              K Offline
              K Offline
              Keith Barrow
              wrote on last edited by
              #13

              Your code would work, but you have repeated LookAround() method, this increase your maintenance overhead if you needed to change one, the chances are you'd need to change the other. Obviously this is a simple example to try and make the principle clear so it doesn't stand up to close scrutiny. Additionally the abstract class adds a semantic meaning : these are all the things that my subclasses can do that are common to all of them.

              Sort of a cross between Lawrence of Arabia and Dilbert.[^]
              -Or-
              A Dead ringer for Kate Winslett[^]

              K 1 Reply Last reply
              0
              • L Lost User

                Abstract class and inheritance is all about building a hierarchy (or family) of classes while Interface is to enforce a contract. Consider this hierarchy of classes. You can create FlyingVehicle as an abstract class.

                Vehicle --> FlyingVehicle --> Helicopter

                Consider another hierarchy of classes. You can create Bird as an abstract class.

                Animal --> Bird --> Eagle

                While the two families of classes are distinct, both the the FlyingVehicle and the Bird classes can implement an Interface called IFlyable.

                interface IFlyable {
                void Fly();
                void Land();
                }

                As you can see in this example, you created two distinct families of classes using Abstract classes and enforced the ability to fly using an interface.

                K Offline
                K Offline
                Krishna Varadharajan
                wrote on last edited by
                #14

                Mr.Shameel, Can you please make those example's little clear, mean to say.. describing interface & abstract class with the same example by inheriting. krishna

                L 1 Reply Last reply
                0
                • K Keith Barrow

                  Your code would work, but you have repeated LookAround() method, this increase your maintenance overhead if you needed to change one, the chances are you'd need to change the other. Obviously this is a simple example to try and make the principle clear so it doesn't stand up to close scrutiny. Additionally the abstract class adds a semantic meaning : these are all the things that my subclasses can do that are common to all of them.

                  Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                  -Or-
                  A Dead ringer for Kate Winslett[^]

                  K Offline
                  K Offline
                  Krishna Varadharajan
                  wrote on last edited by
                  #15

                  Thanks a lot keith, really appreciate your effort to make me understand :) krishna

                  K 1 Reply Last reply
                  0
                  • K Krishna Varadharajan

                    Thanks a lot keith, really appreciate your effort to make me understand :) krishna

                    K Offline
                    K Offline
                    Keith Barrow
                    wrote on last edited by
                    #16

                    Glad to be of help!

                    Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                    -Or-
                    A Dead ringer for Kate Winslett[^]

                    1 Reply Last reply
                    0
                    • G GuyThiebaut

                      Hi Krishna, Please just call me Guy as Mr Guy is too formal for the codeproject ;) An abstract class does not need to implement an interface. An abstract class must be inherited as you cannot create an instance of an abstract class - think of an abstract class as something like a Feline, in Keith's excellent illustration, which is a concept and for which there is no such concrete existence. However there are tigers which are Feline and are very much concrete - so a tiger inherits from the abstract class of Feline. You can just create an abstract class and then inherit from that class to create your instances(without implementing an interface). An abstract class allows you to implement some very general methods such as the LookAround method in Keith's illustration which will not need to be overridden. Abstract classes are a means of writing less code and implementing polymorphism.

                      “That which can be asserted without evidence, can be dismissed without evidence.”

                      ― Christopher Hitchens

                      K Offline
                      K Offline
                      Krishna Varadharajan
                      wrote on last edited by
                      #17

                      Explained very well, thanks a lot guy.. ;) krishna

                      1 Reply Last reply
                      0
                      • K Krishna Varadharajan

                        Mr.Shameel, Can you please make those example's little clear, mean to say.. describing interface & abstract class with the same example by inheriting. krishna

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #18

                        That's the point here, abstract classes and interfaces are not meant to be used interchangeably (although most programming languages allow you to do that). Classes are to build family and interfaces are to enforce contracts, nothing more, nothing less.

                        K 1 Reply Last reply
                        0
                        • L Lost User

                          That's the point here, abstract classes and interfaces are not meant to be used interchangeably (although most programming languages allow you to do that). Classes are to build family and interfaces are to enforce contracts, nothing more, nothing less.

                          K Offline
                          K Offline
                          Krishna Varadharajan
                          wrote on last edited by
                          #19

                          Thank you... krishna

                          1 Reply Last reply
                          0
                          • K Krishna Varadharajan

                            Hi, I know the functionality of Abstract Class & Interface. But, in which situation i can use this. Consider I am starting a new project and I need to design and create a class. So here in which situation I should create AbstractClass or Interface. How to find out which is suitable for particular situation. Please give me some practical situation where I can use and where I can't. krishna

                            J Offline
                            J Offline
                            jschell
                            wrote on last edited by
                            #20

                            krishnavaradharajan wrote:

                            I know the functionality of Abstract Class & Interface.

                            Normally the "functionality" has nothing to do with the decision. You use them because they meet the design needs.

                            krishnavaradharajan wrote:

                            How to find out which is suitable for particular situation.

                            1. Collect some requirements. 2. Create a design. 3. Use the design to implement code. Step 3 is where you decide which one to use based on the objects of the design.

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups