Programming Tutorial: Classes Part 2

esse quam videri
Jump to: navigation, search

Constructors

An important component of a class is its constructor. A constructor is a special method that is called when whenever you declare an object. A constructor has a return type of its respective class. Here's a possible constructor for our dog class:

public dog()
{

}

dog() will return a new instance of object type "dog". As we discussed previously, you create an instance of the dog class by calling:

dog myDog = new dog();

What you didn't realize before is that "new dog()" is calling the constructor and returning an instance of dog.

The constructor should be the first function in your class. This is not necessary, but it is the standard convention and it makes for more readable and organized code. In our dog class from the previous tutorial, we omitted a constructor and everything worked just fine. This is because C# (and in fact most languages) will generate a default constructor if one is not defined. A constructor that does nothing is admittedly pointless, and since constructors are just functions, you can overload them. Here's an example of overloaded constructor:

public dog(string name, int age, int weight)
{
    this.name = name;
    this.age = age;
    this.weight = weight;
}

Let's examine what is going on here. The constructor is getting in 3 parameters, and they happen to have the same member names as the dog class's members from before. We differentiate the two with the "this" keyword. "This" means that we are referring to that specific object's instance of the member. If it's a little easier to understand, here's an equivalent constructor:

public dog(string dogName, int dogAge, int dogWeight)
{
    this.name = dogName;
    this.age = dogAge;
    this.weight = dogWeight;
}

In this case, omitting "this" from the above code would still compile, but it's poor form and an understanding of "this" is important. If you're still a little confused on "this, " here's more information: http://msdn.microsoft.com/en-us/library/dk1507sz(VS.71).aspx

This would be an addition to the first empty constructor, it is not replacing it. This doesn't give us functionality that we didn't have before, but that's because this is a simplified example that shows the basics of class functionality.

Inheritance

Inheritance is an important component of classes and object oriented programming. An inherited object (a class is a code object) is basically a newer version of a previously created object. However, an inherited object can have new members and methods that the original object didn't have. Continuing with our dog example, a dog is a generic classification for a specific type of animal. There are specific breeds of dog however, and they all have unique traits. For example, a Poodle is fluffy whereas a Chihuahua is not. Let's add a string for our fur type:

class dog
{
    public string name, furType;
    public int age, weight;

    // Constructors omitted
}

To make a poodle class that inherits from the dog class, we would write:

class poodle : dog
{

}

We use a colon to say that we are inheriting from a class. The class specified after the colon is the class we are inheriting from. While there is no code to speak of inside of the brackets, we treat the poodle class as though it has all the same code that makes up the dog class. poodle has name, furType, age, and weight. It also has access to any methods defined in dog, so long as their access level is public. Since all poodles are fluffy, we could add that into its constructor, since we know that a poodle's fur type will never be anything other than "fluffy."

class poodle : dog
{
    public poodle()
    {
        furType = "fluffy";
    }
}

Every poodle made will have it's furType set to "fluffy" upon initialization.

An important thing to note is that we can also call dog's constructor. We do that by calling "base" in the same line as poodle's overloaded constructor:

public poodle(string name, int age, int weight) : base(name, age, weight)
{
    furType = "fluffy";
}

The class we are inheriting from is known as the "base class". ": base(name, age, weight)" calls the base class's constructor, while also passing along the variables from the constructor definition. This is useful if we want to use the base constructor and don't want to repeat code, one of the main advantages of objects and inheritance.

We can add methods and members that are unique to poodle and not present in dog. A poodle-exclusive action might be going to a poodle contest. Let's edit poodle to have this function:

class poodle : dog
{
    public poodle()
    {
        furType = "fluffy";
    }

    public void goToAPoodleContest()
    {
        Console.WriteLine(string.Format("{0} went to a poodle contest!", this.name));
    }
}

So now poodle has a method that is not in the original dog class. What it boils down to is that objects that are inherited by other objects act as an effective "template" object. Code can be written once and used in a multitude of ways. If you are writing a program that utilizes a set of objects that can be abstracted into a more general object, you should use inheritance. This also makes code far easier to manage; if you need to change something in a base class, then all objects that inherit from it will be updated as well. Here's our updated program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace classTutorial
{
    class Program
    {
        static void Main(string[] args)
        {

            dog myDog = new dog();

            myDog.name = "Snapple";
            myDog.age = 4;
            myDog.weight = 110;

            Console.WriteLine(
                string.Format("Name:  {0}\r\nAge:  {1}\r\nWeight:  {2}\r\n", 
                myDog.name, myDog.age, myDog.weight));

            myDog.bark();

            poodle myPoodle = new poodle();
            myPoodle.name = "Hercules";
            myPoodle.age = 5;
            myPoodle.weight = 30;

            Console.WriteLine();
            myPoodle.goToAPoodleContest();

            Console.ReadKey();
        }
    }

    class dog
    {
        public string name, furType;
        public int age, weight;

        public dog()
        {

        }

        public dog(string name, int age, int weight)
        {
            this.name = name;
            this.age = age;
            this.weight = weight;
        }

        public void bark()
        {
            Console.WriteLine("Woof!");
        }
    }

    class poodle : dog
    {
        public poodle()
        {
            furType = "fluffy";
        }

        public void goToAPoodleContest()
        {
            Console.WriteLine(string.Format("{0} went to a poodle contest!", this.name));
        }
    }
}