Friday 27 January 2012

What is inheritance?

Inheritance - is the concept of passing the traits of a class to another class.

A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)

Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon. (Reference) 


 Whats the difference between a class and an object?


In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.
Example
Lets create a class named Laptop
public class Laptop
{
  private string sbrand;
  public Laptop() {}
  public Laptop(string name)
  {
    sbrand = name;
  }
}

From our code that references this class, we write...

Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor
Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.

No comments:

Post a Comment