Monday, September 15, 2008

OOP fundamentals in C#

// INHERITANCE //
public class ChildClass : ParentClass
// declare a class to inherit from another
{
public ChildClass() {} // constructor
}
// POLYMORPHISM //

public virtual void PolymorphicMethod()
{
// implementation goes here
// child classes can override the implementation
// b.c. of keyword 'virtual'
}
public override void PolymorphicMethod()

{
// used in child class to override a virtual method of a parent class
// by using keyword 'override'
}

// ENCAPSULATION //

public class MyObjectModel
{
// fields hidden from outside world by limiting scope
private string _Field1;
private string _Field2;

public void UpdateFields()
{
// class method updates private members
_Field1 = "Field1";
_Field2 = "Field2";
}
}

// ABSTRACT CLASS //

public abstract class MyAbstractClass
// abstract class can have 0 or more methods abstract
{
private string _Field1; // member variable
public string MyConcreteMethod()
// abstract class can provide concrete methods too
{ // implementation provided
}
abstract public string MyAbstractMethod();
// no implementation provided
}

public class MyConcreteClass : MyAbstractClass

// class that inherits abstract class
{
public override string MyAbstractMethod()
{ // implementation of inherited, abstract method
//(required)
}
}
// INTERFACE //

interface MyInterface
// interface must have all methods abstract
// and no member variables
{
void MyAbstractMethod1(); // no implementation provided
string MyAbstractMethod2();
}
public class MyClass : Parent Class, MyInterface

// inherits both class and interface
{
public MyClass() { } // constructor
public void MyAbstractMethod1()
{ // must provide implementation
}
public string MyAbstractMethod2()
{ // must provide implementation
}
}

2 comments:

fatrobot said...

so what for like does that supposed to mean?

Butchie said...

WTF? Are you trying to scare us off?