Web Design and Web Development Forum

  1. #1
    Join Date
    Sep 2005
    Location
    UK
    Age
    27
    Posts
    807
    Rep Power
    0
  2. bfsog is on a distinguished road
  3. C# Guide to classes and inheritance

    Name: Introduction to inheritance
    Need to know: The examples are in C#.NET however the topics discussed should be easily portable to any OO language.

    In this tutorial I hope to give you an insight into a specific area of Object Oriented Programming. That area is Inheritance.

    Inheritance in a nutshell is: a way to create new classes (therefore objects) by using a class(es) that has already been defined.

    Brief overview of classes and objects

    A class is a programming construct used to group related attributes and methods.
    An object is an instance of a class.

    Example: a class may be Person with attributes like name, age, location and methods like wakeUp, goToWork and so on.
    An object of that class could be you, me, anybody.

    Step 1 - Our parent class.

    Below is a class which I just created. It does not know it yet but ParentClass will soon be a parent! Here is the class.

    Code:
    public class ParentClass
    {
    
        public ParentClass()
        {
            Console.WriteLine("I am the Constructor of ParentClass.");
        }
    
        public int addNumbers(int num, int num2)
        {
            return num + num2;
        }
    
    }
    Listing 1 explained:

    That class has a Constructor and one method. The method named addNumbers returns the value of num + num2.

    You should note that because the class ParentClass has a constructor, when we create an instance of the class the constructor will execute.

    Step 2 - Our child class.

    The main benefit of creating a new class from an already defined class is you can reuse existing code.

    Lets say we want to be able to add 2 numbers together in another class. Why rewrite the same functionality when we have a class that already does that?

    So, we want to create a new class that can access ParentClass's methods and attributes. Heres how.

    Code:
    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("I am the Constructor of ChildClass which is infact a ParentClass.");
        }
    
        public static void Main()
        {
            ChildClass child = new ChildClass();
            Console.WriteLine(child.addNumbers(5, 12).ToString());
            Console.ReadLine();
        }
    }
    Listing 2 explained:

    The first line
    Code:
    public class ChildClass : ParentClass
    creates a new class called ChildClass which inherits the methods and attributes of ParentClass.

    ChildClass has a Constructor and a Main() method. When Main() is called because this class is a child of ParentClass, the constructor of ParentClass is executed first, then the Constructor of ChildClass and then addNumbers.

    The output of executing this file is:
    I am the Constructor of ParentClass.
    I am the Constructor of ChildClass which is infact a ParentClass.
    17
    Theres one more thing I want to show you.

    As you can see, ChildClass does not have a method named addNumbers so it uses the addNumbers method in ParentClass. That is good, it saves repeating code.

    However, what if for a particular instance of a class I want to do something different in addNumbers but I still want to inherit the methods and attributes of ParentClass (for example if the ParentClass has 10 methods, your child class needs to use 9 methods but one method needs to have different logic).

    It would be stupid to copy the 9 methods directly into the new child class, so you use the already created class. You need to create 1 new method in the child class. Heres how:

    Code:
    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("I am the Constructor of ChildClass which is infact a ParentClass.");
        }
    
        public new int addNumbers(int num, int num2)
        {
            return num - num2;
        }
    
        public static void Main()
        {
            ChildClass child = new ChildClass();
            Console.WriteLine(child.addNumbers(5, 12).ToString());
            Console.ReadLine();
        }
    }
    Listing 3 explained.

    This listing is exactly the same as Listing 2 except I have created a method called addNumbers. Note the keyword new in the
    Code:
    public new int addNumbers(int num, int num2)
    line. This tells the class that this method has the same name as it's parents method.

    So when I run this file the output is:

    I am the Constructor of ParentClass.
    I am the Constructor of ChildClass which is infact a ParentClass.
    -7
    The ChildClass has a method named addNumbers so it executes that rather than using it's Parents method of the sane name.

    I hope this has helped someone gain an understanding of classes and inheritance.
    Reply With Quote Reply With Quote
  4. #2
    Join Date
    Dec 2006
    Location
    University of York, UK
    Age
    22
    Posts
    1,837
    Rep Power
    7
  5. Mike Tomasello is on a distinguished road
  6. Re: C# Guide to classes and inheritance

    Could have posted this a day earlier. I was trying to remember what the inheritance 'operator' in C# was only yesterday! :p (though it took about 5 seconds to get the answer from Google).

    I don't really like the use of the 'new' keyword in method definitions that override its parent class. Jolly nice of C# to mollycoddle coders, but I feel it taints the elegance of polymorphism (I think it's optional, but not using it generates warnings?).
    Reply With Quote Reply With Quote
  7. #3
    Join Date
    Sep 2005
    Location
    UK
    Age
    27
    Posts
    807
    Rep Power
    0
  8. bfsog is on a distinguished road
  9. Re: C# Guide to classes and inheritance

    Yes indeed, it's not needed but you will get a warning if you omit it. While I agree that it slightly mollys us, I guess it is justified as it is a new method.

    For the record if you omit the new keyword the method of the child/sub class will execute and not the parent's method.
    Reply With Quote Reply With Quote
  10. #4
    waheedahmed's Avatar
    Join Date
    Apr 2006
    Location
    Pakistan
    Posts
    982
    Rep Power
    7
  11. waheedahmed is on a distinguished road
  12. Re: C# Guide to classes and inheritance

    Quote Mike_Tomasello originally posted:
    I don't really like the use of the 'new' keyword in method definitions that override its parent class.
    In the example given by bfsog, the addNumbers method in child class is not overriding the addNumbers method in the parent class.

    The method in the parent class is not virtual hence it can't be overriden.

    What the new keyword in a method definition does is to create a completely new method that has no link what-so-ever with the method in the parent class.

    To override a method, the method should be virtual and the override keyword is used.
    Last edited by waheedahmed; 08-06-2008 at 07:54 AM.

    Reply With Quote Reply With Quote
  13. #5
    Join Date
    Dec 2006
    Location
    University of York, UK
    Age
    22
    Posts
    1,837
    Rep Power
    7
  14. Mike Tomasello is on a distinguished road
  15. Re: C# Guide to classes and inheritance

    Quote waheedahmed originally posted: View Post
    In the example given by bfsog, the addNumbers method in child class is not overriding the addNumbers method in the parent class.

    The method in the parent class is not virtual hence it can't be overriden.

    What the new keyword in a method definition does is to create a completely new method that has no link what-so-ever with the method in the parent class.

    To override a method, the method should be virtual and the override keyword is used.
    Isn't that a little bit pedantic? There is a difference, but they are both still 'overriding' in the classic sense, just not in the C# keyword sense, which doesn't impact this particular use case at all. It's my understanding the difference would only come into play if ParentClass child = new ChildClass(); was used.

    I am a C# novice, so feel free to correct me if that's a load of ****.
    Last edited by Mike Tomasello; 08-06-2008 at 08:26 AM.
    Reply With Quote Reply With Quote
  16. #6
    waheedahmed's Avatar
    Join Date
    Apr 2006
    Location
    Pakistan
    Posts
    982
    Rep Power
    7
  17. waheedahmed is on a distinguished road
  18. Re: C# Guide to classes and inheritance

    but they are both still 'overriding' in the classic sense, just not in the C# keyword sense,
    I don't understand what that means :)

    I don't really like the use of the 'new' keyword in method definitions that override its parent class.
    which doesn't impact this particular use case at all.
    I never said that bfsog's use of new was wrong, I was only trying to correct you because in C# new and override are very different and their use affects your application's behaviour a lot.


    If you were working with a third-party component that defines a virtual method 'Connect', and you override this method in Application A but hide it (new) in Application B, then if the component developers were to remove 'Connect' - Application A will stop working but Application B will continue to work normally. The new keyword is just to make sure the developer is aware that he is hiding a method, your code will compile fine (you'll only get a warning) even if you omit the new keyword.

    Read more:
    Versioning with the Override and New Keywords

    C# is a component-oriented language so you should know when to use new and override.
    Last edited by waheedahmed; 08-06-2008 at 11:02 AM.

    Reply With Quote Reply With Quote
  19. #7
    Join Date
    Dec 2006
    Location
    University of York, UK
    Age
    22
    Posts
    1,837
    Rep Power
    7
  20. Mike Tomasello is on a distinguished road
  21. Re: C# Guide to classes and inheritance

    I don't understand what that means
    C# is a component-oriented language so you should know when to use new and override.
    That is what I mean. While the keywords are different, they are still both overriding. Use of the override keyword takes it further and seems generally more useful for more advanced applications of polymorphism. When I said that the method definitions override its parent class, I meant that in the sense of OO terminology not a reference to the C# keyword.
    Reply With Quote Reply With Quote
  22. #8
    waheedahmed's Avatar
    Join Date
    Apr 2006
    Location
    Pakistan
    Posts
    982
    Rep Power
    7
  23. waheedahmed is on a distinguished road
  24. Re: C# Guide to classes and inheritance

    ...they are still both overriding.
    if (your_overriding == (overriding && hiding))
    {
    I_agree();
    }
    else
    {
    I_dont_agree();
    }


    Use of the override keyword takes it further
    Takes what further?


    and seems generally more useful for more advanced applications of polymorphism.
    and seems generally more useful
    'if' seems generally more useful than 'break' for creating conditional statements, so lets use the keywords interchangeably or better still get rid of break completely.

    Simply because 'new' and 'override' have the same output in bfsog's code doesn't mean they are the same, I have already explained the difference.


    for more advanced applications of polymorphism
    'new' is mainly for aiding C#'s component-orientation and not it's object-orientation, so I can't see why you are comparing the two.

    And as far as polymorphism is concerned, if you do interface based development then new can be equally as useful as override, it's all based on what the conditions are.

    Reply With Quote Reply With Quote
  25. #9
    gorda001's Avatar
    Join Date
    Jun 2005
    Location
    <0x79a3f6>
    Posts
    4,851
    Rep Power
    11
  26. gorda001 is on a distinguished road
  27. Re: C# Guide to classes and inheritance

    Let me have a go at explaining. C# has the "new" and "override" keywords. They are mutually exclusive - you cannot have a "new override" method. However, a "new" method is also overriding by the standard definition, hence causing the confusion.
    Last edited by gorda001; 08-06-2008 at 01:04 PM.
    Reply With Quote Reply With Quote
  28. #10
    gorda001's Avatar
    Join Date
    Jun 2005
    Location
    <0x79a3f6>
    Posts
    4,851
    Rep Power
    11
  29. gorda001 is on a distinguished road
  30. Re: C# Guide to classes and inheritance

    I am trying to clear up a misunderstanding, not create argument. Although YC certainly does need more arguments ;)
    Reply With Quote Reply With Quote

Similar Threads

  1. Classes
    By Adamwts in forum PHP Scripting
    Replies: 7
    Last Post: 04-22-2007, 02:16 AM
  2. Abstract classes and templates help
    By Umang in forum PHP Scripting
    Replies: 37
    Last Post: 12-22-2006, 09:37 PM
  3. Classes
    By King Kovifor in forum PHP Scripting
    Replies: 17
    Last Post: 10-31-2006, 07:47 PM
  4. Multiple Inheritance or Mixins or something
    By _jameshales in forum PHP Scripting
    Replies: 4
    Last Post: 11-27-2005, 03:32 AM