Tuesday, September 25, 2012

Implement Interfaces & Use Abstract Classes





Interfaces & Abstract Classes

  • Write Interface definitions and class definitions that implement them.
  • Write abstract class definitions and derived classes that inherit from them.
Interfaces:
  • An interface just declares methods, which must be provided by any class that implements the interface.
  • A virtual method must have a body. An method declared in an interface does not.
Generally your best tool for separation of interface and implementation.
  • The interface is public.
  • Implementation is private.
  • Users see only the interface.
How to Define an Interface:

interface IShape
{
void Draw();
double Area();
}

Restrictions:
An interface never includes implementation.
Consequently:
You cannot instantiate an instance.

  • No fields
  • No constructors (or destructors)
  • No access modifiers (public, private). methods automatically public
  • No type definitions inside interface definition.  enums, structs, classes, etc.
  • Cannot inherit from a class or a struct.
Classes and structs must have implementations.
Interface IShape:
interface IShape
{
void Draw();
double Area();
}

Implementing an Interface:

Inherit an interface just like a base class
class Square : IShape
{
private double Size; // Length of each side
public Square (double size)
{
Size = size;
}

public double Area()
{
return Size * Size;
}
public void Draw()
{
Console.WriteLine ("Square Draw method called");
}
}
Example: Using a Class that Implements an Interface
class Program
{
static void Main(string[] args)
{
Square sq = new Square(10);
double area = sq.Area();
Console.WriteLine ("Area = " + area);
sq.Draw();
Console.ReadLine();
}
}

Output:
But an interface cannot be instantiated
class Class1
{
static void Main(string[] args)
{
IShape sq;
sq = new IShape();
}
}
This gets a compile error.

This compiles and runs:
class Program
{
static void Main(string[] args)
{
IShape sq = new Square(10);
double area = sq.Area();
Console.WriteLine("Area = " + area);
sq.Draw();
Console.ReadLine();
}
}
Program in Action

Abstract Classes:

Often you will have several different classes that implement a given interface:

e.g. Circle, Square, Triangle, ...

The classes may have some methods that are identical

Examples: String Name();
int ID();

Replicating functionality in multiple classes is a bad idea.
Solution is to define an abstract class.

Provides implementation for methods that are common to derived classes.
Like an interface, cannot be instantiated. Exists only to be inherited.

Derived classes inherit from the abstract class.

Implement methods that are different for each kind of derived class.

An Abstract Class:

abstract class Default_Shape
{
protected String name;
static int next_id = 1;
protected int id;
protected Default_Shape(String name_)
{
name = name_;
id = next_id++;
}

public int ID()
{
return id;
}
public String Name()
{
return name; }

Some Derived Classes:

class Square : Default_Shape, IShape
{
private double Size; // Length of each side
public Square(double size, String name_) : base(name_)
{
Size = size;
}
public double Area()
{
return Size * Size;
}

Square
public void Draw()
{
Console.WriteLine("Square Draw() called." +
" ID = " + id +
" Size = " + Size);
}
Class Circle
class Circle : Default_Shape, IShape // Same bases
{
private double radius; // Unique field
public Circle (double radius_,
String name_) : base (name_)
{
radius = radius_;
}

public double Area()
{
return Math.PI*radius*radius;
}

public void Draw()
{
Console.WriteLine ("Circle Draw() called." +
" ID = " + id.ToString() +
" radius = " + radius.ToString() );
}
}

Using the Derived Classes:

Square sq1; // Declarations

Circle c1;
IShape ishape1;
IShape ishape2;
sq1 = new Square(1, "sq1"); // Instantiation
c1 = new Circle (1, "c1");
ishape1 = new Square(10, "ishape1");
ishape2 = new Circle(10, "ishape2");
sq1.Draw(); // Method calls
c1.Draw();
ishape1.Draw();
ishape2.Draw();

Output:
Working with Multiple Interfaces.In C#, a class can have at most one base class
BUT can implement any number of interfaces

Syntax:
class Square : Default_Shape, IShape, IDisposable, IComparable
{
...
}

A class must implement all methods in all interfaces that it inherits.

Summary:

Inheritance is one of the key concepts of object oriented programming.
  • A class can inherit
  • A base class
  • Any number of interfaces Functionality common to multiple classes can be factored out to an abstract base class that all inherit.
  • Avoid replication.

Monday, September 24, 2012

Constructor, Destructor,Inheritance and Polymorphism




Constructor, Destructor & Gerbage Collection

 Constructor:

  • Constructors are class methods that are executed when an object of a Class or Struct is created.
  • They have the same name as the class or struct, and usually initialize the data members of the new object.
  • A class or struct may have multiple constructors that take different arguments.
  • Constructors enable the programmer to set default values, limit instantiation and write code that is flexible and easy to read.
  • If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values .
  • Static classes and structs can also have constructors.

Constructor-example:

public class Time

   {

       int Year;

       int Month;

       int Date;

       int Hour;

       int Minute;

       int Second;

public void DisplayCurrentTime( )

      {

Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}“,   Month, Date, Year, Hour, Minute, Second);

      } 

 

Gerbage Collectin(GC):

GC frees up memory used by those objects which can no longer be accessed by your runtime code.

Gerbage Collection

void A()
{

    B();
    int i = 10;
 }

void B()
{
    C c = new C();
   Console.WriteLine(c.Name);
}

  • In the above example once the control comes to the line int i = 10; in function A(), there is no way for the system to access the object c created in function B(). This is an object which is eligible for Garbage Collection. So the next time when the GC thread runs it can cleanup the memory allotted to the object c.

Destructor:

  • Destructors are used to destruct instances of classes.
  • Destructors cannot be defined in structs. They are only used with classes.
  • A class can only have one destructor.
  • Destructors cannot be inherited or overloaded.
  • Destructors cannot be called. They are invoked automatically.
  • A destructor does not take modifiers or have parameters.

class Car

{

    ~Car()  // destructor

  {

        // code

   }

}

  • The C# compiler translates it to:

    protected override void Finalize()

{

    try

    {

        // Code

    }

    finally

    {

        base.Finalize();

    }

}

 

 

Inheritance and Polymorphism

Inheritance:

  • Inheritance allows a software developer to derive a new class from an existing one.
  • The existing class is called the parent, super, or base class.
  • The derived class is called a child or subclass.
  • The child inherits characteristics of the parent.
    • Methods and data defined for the parent class.

  • The child has special rights to the parents methods and data.
    • Public access like any one else

    • Protected access available only to child classes (and their descendants).

  • The child has its own unique behaviors and data.

  • Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class.
  • Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent.

Examples: Base Classes and Derived Classes

Declaring a Derived Class

  • Define a new class DerivedClass which extends BaseClass.

    class BaseClass

  {

      // class contents

}

  class DerivedClass : BaseClass

  {

      // class contents

}

Controlling Inheritance:

  • A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member.
  • Variables and methods declared with private visibility are not accessible in the child class
    • However, a private data member defined in the parent class is still part of the state of a derived class.

  • Variables and methods declared with public visibility are accessible
  • There is a third visibility modifier that helps in inheritance situations: protected.

The protected Modifier:

  • Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class.

Single Inheritance:

  • C# supports single inheritance, meaning that a derived class can have only one parent class.

Overriding Methods:

  • A child class can override the definition of an inherited method in favor of its own.That is, a child can redefine a method that it inherits from its parent
  • The new method must have the same signature as the parent's method, but can have a different implementation.
  • The type of the object executing the method determines which version of the method is invoked.

Class Hierarchies:

  • A child class of one parent can be the parent of another child, forming a class hierarchy
  • An inherited member is continually passed down the line
    • Inheritance is transitive.

  • Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.

References and Inheritance:

  • An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance.
  • For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object.
Holiday day;
day = new Holiday();
day = new Christmas();
Dynamic Binding
  • A polymorphic reference is one which can refer to different types of objects at different times.
  • The type of the actual instance, not the declared type, determines which method is invoked.
  • Polymorphic references are therefore resolved at run-time, not during compilation.
    • This is called dynamic binding.

Dynamic Binding:

  • Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides it).
  • Now consider the following invocation:

day.Celebrate();

  • If day refers to a Holiday object, it invokes the Holiday version of Celebrate; if it refers to a Christmas object, it invokes the Christmas version

Overriding Methods:

  • C# requires that all class definitions communicate clearly their intentions.
  • The keywords virtual, override and new provide this communication.
  • If a base class method is going to be overridden it should be declared virtual.
  • A derived class would then indicate that it indeed does override the method with the override keyword.

Sealed Method:

What if you don't want anyone to derive classes from your class?
Mark class as sealed.
sealed class Square : Default_Shape
{...}
A program that atttempts to define a derived class based on Square will get a compile error.
All structs are implicitly sealed.

You can also mark a method as sealed.
  • This prevents any derived class from overriding that method.
  • Normally a method that overrides a virtual method in a base class is itself virtual.
  • The method can be re-implemented again and again in successive derived functions. “sealed” puts an end to this.

Overloading vs. Overriding:

  • Overloading deals with multiple methods in the same class with the same name but different signatures
  • Overloading lets you define a similar operation in different ways for different data
  • Example:

int foo(string[] bar);

int foo(int bar1, float a);

  • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature.
  • Overriding lets you define a similar operation in different ways for different object types
    Example:

class Base {

    public virtual int foo() {} }

class Derived {

    public override int foo() {}}

 

Polymorphism via Inheritance

The System.Object Class

  • All classes in C# are derived from the Object class
    • If a class is not explicitly defined to be the child of an existing class, it is a direct descendant of the Object class.
  • The Object class is therefore the ultimate root of all class hierarchies.
  • The Object class defines methods that will be shared by all objects in C#, e.g.,
    • ToString: converts an object to a string representation

    • Equals: checks if two objects are the same

    • GetType: returns the type of a type of object

  • A class can override a method defined in Object to have a different behavior, e.g.,
    • String class overrides the Equals method to compare the content of two strings

 

Saturday, September 22, 2012

 

Basic of C#

A computer program is a set of instructions that you write totell a computer what to do 
¡ Programmers do not use machine language when creating computer programs. Instead, programmers tend to usehigh-level programming languages. 
¡ Each high-level language has its own syntax and limited set of vocabulary that is translated into machine code by a compiler.  
¡ In addition to understanding syntax, a programmer must also understand programming logic. 
¡The goal of C# is to provide a simple, safe  modern, object-oriented, Internet-centric, high-performance language for .NET development.
  
 ¡In .NET, programs are not compiled into executable files; they are compiled into Microsoft Intermediate Language (MSIL) files, which the CLR then executes. The MSIL (often shortened to IL) files that C# produces are identical to the IL files that other .NET languages produce; the platform is language- agnostic. A key fact about the CLR is that it is common; the same runtime supports development in C# as well as in VB.NET. 
 ¡C# code is compiled into IL when you build your project. The IL is saved in a file on disk. When you run your program, the IL is compiled again, using the Just In Time (JIT) compiler .The result is machine code, executed by the machine's processor. 

¡The CLS means that all .NET languages produce very similar IL code. As a result, objects created in one language can be accessed and derived from another. Thus it is possible to create a base class in VB.NET and derive from it in C#.
    
¡The essence of object-oriented programming is the creation of new types. A type represents a thing. Sometimes the thing is abstract, such as a data table or a thread; sometimes it is more tangible, such as a button in a window. 

¡A type defines the thing's general properties and behaviors.

¡As in many object-oriented programming languages, in C# a type is defined by a
 class, while the individual instances of that class are known as objects.
  
¡ At the heart of any object-oriented language is its support for defining and working with classes.

¡ C# contains keywords for declaring new classes and their methods and properties, and for implementing encapsulation, inheritance, and polymorphism, the three pillars of object-oriented programming.






 

  • The essence of object-oriented programming is the creation of new types. A type represents a thing. Sometimes the thing is abstract, such as a data table or a thread; sometimes it is more tangible, such as a button in a window. 
  • A type defines the thing's general properties and behaviors. 
  • As in many object-oriented programming languages, in C# a type is defined by a class, while the individual instances of that class are known as objects. 
  • At the heart of any object-oriented language is its support for defining and working with classes.
  • C# contains keywords for declaring new classes and their methods and properties, and for
    implementing encapsulation, inheritance, and polymorphism, the three pillars of object-oriented
    programming. 

  • A class is a blueprint that describes an object and defines attributes and operations for the object
    Classes use abstraction to make available only the elements essential to defining the object 
  • Classes use encapsulation to enforce an abstraction.


An object is an instance of a class.
  Objects have the following qualities:
  • Identity: Objects are distinguishable from
  • Behavior: Objects can perform tasks
  • State: Objects store information that can vary over time.

 Fields
-The state of an object or type

Method
-Constructors
-Functions
-Properties (smart fields)

Members come in two basic forms
Instance – per object data and methods
•Default
Static – per type data and methods
•Use the static keyword



class HelloWorld
{
static void Main( )
{
// Use the system console object
System.Console.WriteLine("Hello World");
}
}





  • A class has both properties and behaviors.
  • Behaviors are defined with member methods;
  • Member methods are sometimes called member functions that defines what a class can do or how it behaves.
  • The CLR calls Main( ) when a program starts.
  • Main( )is the entry point for your program
  • Every C# program must have a Main( ) method. 
Inheritance specifies an “is-a-kind-of” relationship. Multiple classes share the same attributes and operations, allowing efficient code reuse 

 Examples:
  • A customer “is a kind of” person
  •  An employee “is a kind of” person


¡ A derived class inherits from a base class.

¡ Properties, methods, data members, events, and event handlers can be inherited (dependent on scope) .
¡ Keywords

§Inherits – inherits from a base class .

§NotInheritable – cannot be inherited from .

§MustInherit – instances of the class cannot be created; must be inherited from as a base class.