Wednesday, April 23, 2008

Inheritance and Polymorphism

Inheritance means if class B inherits from class A then B has class A's attributes and behavior. That means class B inherits class A's members (fields, properties and methods).
We call the class A the base class or the parent class and the class B the derived class or the child class.


class A
{
    ...
}

class B : A // class B inherits from class A.
{
    ...
}


As a result of inheritance, if class B inherits from class A then class B can substitute class A. This is because the inheritance relationship is an "is-a" relationship. The class B is an A.
But this is one-directional relation, class B is an A but class A is not a B.


A ref_a = new A();
B ref_b = new B();
ref_a = ref_b; // because B is an A so we can put a B instead of an A
//ref_b = ref_a ; // Error. This won't compile because an A is not a B (but a B is an A)



So, you might have a function that returns an A but it can return a B because B is an A. The same concept is applied if you have a function that takes an A as a parameter but you can pass a B instead.


Class hierarchy


A class hierarchy represents the sequence of inheritance of a class. Let's take a look at the System.Windows.Forms.Label's inheritance path in the following hierarchy.


System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Windows.Forms.Control
         System.Windows.Forms.Label
       System.Windows.Forms.ButtonBase
         System.Windows.Forms.Button
         System.Windows.Forms.CheckBox
         System.Windows.Forms.RadioButton

A Label is a Control and a Control is a Component, So a Label is a Component. You got the idea, a Label is a MarshalByRefObject and is an Object. All .Net classes implicitly inherits from the System.Object class


Polymorphism and Overriding


Polymorphism is the ability of objects of different classes to respond to method calls of the same signature, each one according to an appropriate class-specific behavior. This is often achieved by inheritance.


Overriding allows you to alter behaviors inherited from the parent of the class.


To override a function in the child class it must be "overridable" in the base class. It must be marked with the virtual keyword in the base class, in fact the equivalent Visual Basic keyword is actually Overridable which is more meaningful. Of course, an overridable function can not be private so that it's exposed to the child class. We shall discuss access modifiers later.


class A
{
    public virtual string Foo()
    {
        return "A's foo.";
    }
    ...
}

class B : A

    public override string Foo() 
    { 
        return "B's foo."
    }
    ...
}



A ref_a = new A();
B ref_b = new B();
ref_a = ref_b;
Console.WriteLine(ref_a.Foo()); // "B's foo."


To understand better the overriding behavior, we shall discuss the this keyword and base.


this vs. base


The this keyword represents the instance of the object being instantiated from the current class. Whether it's a base class or a derived class, it doesn't matter.


The base keyword represents the direct parent of the class which the object is being instantiated from.


So, you use the this keyword to explicitly reach the members of the same class, and you use the base keyword to explicitly reach the members of the parent of the class.


Let's get back to the previous code snippet and modify it a little bit to see what does it all mean.


class A

    public virtual string Foo() 
    { 
        return "A's foo.";
    }
    ...
    public void Poo1()
    {
        // Console.WriteLine(Foo()); // the same as the next line
        Console.WriteLine(this.Foo()); // "A's foo."
    }
}

class B : A

    public override string Foo() 
    { 
        return "B's foo.";
    }
    ...
    public void Poo2()
    {
        Console.WriteLine(base.Foo()); // "A's foo."
        // Console.WriteLine(Foo()); // the same as the next line
        Console.WriteLine(this.Foo()); // "B's foo."
    }
}


From the outside.


A ref_a = new A();
ref_a.Foo(); // "A's foo."
B ref_b = new B();
ref_b.Foo(); // "B's foo."
ref_a = ref_b;
ref_a.Foo(); // "B's foo." // it goes down the class hierarchy


Notice that at the previous line B's Foo is called instead of A's. That's because if a function is virtual and is called from a reference to the base (it's treated as the base). It goes down the class hierarchy whenever is possible. This will become clearer when discussing type casting.


http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

Sunday, April 13, 2008

HTML and CSS

A while ago I was adjusting the blog's CSS to colorize code (mainly C# for now) snippets and I made a post as a test. And someone asked in a comment what CSS was. So, this is a brief introduction about HTML and CSS and some useful links at the end of the post.

HTML (Hyper Text Markup Language)

HTML is a markup language used for writing webpages. It consists of nested tags to describe the structure of text-based information.

HTML syntax is pretty simple. HTML consists of tags. A tag is some text surrounded by angle brackets like the tag <head>. Each tag has an end tag like </head>

Here is a Hello World HTML page. Copy-paste the code in notepad and save the file as "Hello.html" and make sure the extension is .html or .htm but not .txt


<html>
    <head>
        <title>My first HTML page</title>
    </head>
    <body>
        Hello, <b>world!</b>
    </body>
</html>

CSS (Cascading Style Sheets)

In the previous Hello World example. You see the <b> and </b> surrounding "world!". This tag mean the text is bold. Other tags like <font> , <i> ... and attributes are used to format the text in the browser. But hard coding formatting and styles into HTML is hard and not customizable.

CSS is a stylesheet language to describe the presentation of markup language documents. Instead of hard coding embedded styles or tags in HTML you can define a styles for the page and/or link to external .css files.

In the previous HTML code you can set the background color of the body of the document like this.


<body style="background-color: Red; font-size: large">
    Hello, <p>world!</p>
</body>

Or, you can define write the previous page as.


<html>
    <head>
        <title>My first HTML page</title>
        <style type="text/css">
            body {
              background-color: Red;
              font-size: large
            }
        </style>
    </head>
    <body>
        Hello, <b>world!</b>
    </body>
</html>



http://www.w3schools.com/html/default.asp
http://www.w3schools.com/Css/default.asp
http://www.codeproject.com/KB/HTML/htmlbeginner.aspx
http://www.codeproject.com/KB/HTML/cssbeginner.aspx

Wednesday, April 9, 2008

Encapsulation and Information Hiding

Encapsulation means hiding the implementation details of the class from other objects and separating the class's implementation from it's interface.


A class's interface is the parts of the class which is exposed to other classes. It's related to but not the same as interfaces like IEnumerable. It's the way an object of the class is exposed to other objects and which members are public, protected or private.


There are two kind of object's interfaces; the parts of the object that is exposed to every other object is called "public interface", and the parts of the object which is only exposed to derived object via inheritance is called "protected interface".


Creating a well defined interface is an essential step in a good object oriented design.


Why encapsulate?


  • Hide implementation details.

  • Maintain the same object's interface while the inner implementation can change without forcing the clients of the object to change the way they consume it.

  • Encapsulation helps abstraction so you will deal with object at a high level of details, so that you use objects like a Button or data Connection as a "black box" and build more complex software with it.

Example; The interface of a  Stack class is that it has "Push", "Pop" and "Peek" method. Other object don't care how the Stack class is implemented, all they care is its interface.
If the stack was implemented using an ArrayList and the developer wants to change it to use a LinkedList instead, all he has to do is to change the inner implementation and leave the interface unchanged, so that all the code outside of the class will continue to work unchanged.


Another example; you may want to write a log file, you write a class to handle logging to the file. The Log class would have a method public void Log(string message) that will handle writing to the log file, take care of the file structure, add date and time to the log entry ...etc.


One more example; You would use Enums to hide the underlying datatype of a type. Let's see this code snippet.


public enum AccountType : byte // define a new type called AccountType with underlying type byte. by default, the underlying type is integer.
{
    Administrator = 0,
    Limited = 1,
    Guest = 2
}


So, you now have a new data type the AccountType type which is actually a byte. The AccountType enum has 3 constants Administrator, Limited and Guest with values 0, 1 and 2 respectively.


AccountType type = AccountType.Administrator; // type = 0 since Administrator = 0 in the enumeration

type = (AccountType)2; // explicit type cast from int (which will be converted implicitly to byte) to AccountType

byte b = (byte)type; // explicit type cast from AccountType to byte



http://en.wikipedia.org/wiki/Information_hiding
Code Complete 2nd Edition by Steve McConnell

Wednesday, April 2, 2008

CSS Test

This is just a test for the blog's CSS.


// comment
static class Program
{
   [STAThread]
   static void Main()
   {
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Form1());
  }
}