30
What is OOP? OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts. In order to clearly understand the object orientation, let’s take your hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it. What is Encapsulation (or Information Hiding)? The encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do. In order to modularize/ define the functionality of a one class, that class can uses functions/ properties exposed by another class in many different ways. According to Object Oriented Programming there are several techniques, classes can use to link with each other and they are named association, aggregation, and composition.

What is OOP

Embed Size (px)

DESCRIPTION

programming language

Citation preview

Page 1: What is OOP

What is OOP?OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts.

In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.

What is Encapsulation (or Information Hiding)?The encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do.

In order to modularize/ define the functionality of a one class, that class can uses functions/ properties exposed by another class in many different ways. According to Object Oriented Programming there are several techniques, classes can use to link with each other and they are named association, aggregation, and composition.

There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.

 Collapse | Copy Code Collapse | Copy Code

IStudent myStudent = new LocalStudent();IStudent myStudent = new ForeignStudent();

Page 2: What is OOP

According to the sample above (let’s assume that LocalStudent and ForeignStudent are implemented by the IStudent interface) we can see how LocalStudent and ForeignStudent are hiding their, localize implementing information through the IStudent interface.

What is Abstraction and Generalization?Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.

While abstraction reduces complexity by hiding irrelevant detail, generalization reduces complexity by replacing multiple entities which perform similar functions with a single construct. Generalization is the broadening of application to encompass a larger domain of objects of the same or different type. Programming languages provide generalization through variables, parameterization, generics and polymorphism. It places the emphasis on the similarities between objects. Thus, it helps to manage complexity by collecting individuals into groups and providing a representative which can be used to specify any individual of the group.

Abstraction and generalization are often used together. Abstracts are generalized through parameterization to provide greater utility. In parameterization, one or more parts of an entity are replaced with a name which is new to the entity. The name is used as a parameter. When the parameterized abstract is invoked, it is invoked with a binding of the parameter to an argument.

What is an Abstract class?Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be used as a super-class for other classes that extend the abstract class. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties.

Abstract classes are ideal when implementing frameworks. As an example, let’s study the abstract class named LoggerBase below. Please carefully read the comments as it will help you to understand the reasoning behind this code.

 Collapse | Copy Code

 Collapse | Copy Code

Page 3: What is OOP

public abstract class LoggerBase{ /// <summary> /// field is private, so it intend to use inside the class only /// </summary> private log4net.ILog logger = null;

/// <summary> /// protected, so it only visible for inherited class /// </summary> protected LoggerBase() { // The private object is created inside the constructor logger = log4net.LogManager.GetLogger(this.LogPrefix); // The additional initialization is done immediately after log4net.Config.DOMConfigurator.Configure(); }

/// <summary> /// When you define the property as abstract, /// it forces the inherited class to override the LogPrefix /// So, with the help of this technique the log can be made, /// inside the abstract class itself, irrespective of it origin. /// If you study carefully you will find a reason for not to have “set” method here. /// </summary> protected abstract System.Type LogPrefix { get; }

/// <summary> /// Simple log method, /// which is only visible for inherited classes /// </summary> /// <param name="message"></param> protected void LogError(string message) { if (this.logger.IsErrorEnabled) { this.logger.Error(message); } }

/// <summary> /// Public properties which exposes to inherited class /// and all other classes that have access to inherited class /// </summary> public bool IsThisLogError { get { return this.logger.IsErrorEnabled; } }}

The idea of having this class as an abstract is to define a framework for exception logging. This class will allow all subclass to gain access to a common exception logging module and will facilitate to easily replace the logging library. By the time you define

Page 4: What is OOP

the LoggerBase, you wouldn’t have an idea about other modules of the system. But you do have a concept in mind and that is, if a class is going to log an exception, they have to inherit the LoggerBase. In other word the LoggerBase provide a framework for exception logging.

Let’s try to understand each line of the above code.

Like any other class, an abstract class can contain fields, hence I used a private field named logger declare theILog interface of the famous log4net library. This will allow the Loggerbase class to control, what to use, for logging, hence, will allow changing the source logger library easily.The access modifier of the constructor of the LoggerBase is protected. The public constructor has no use when the class is of type abstract. The abstract classes are not allowed to instantiate the class. So I went for the protected constructor.The abstract property named LogPrefix is an important one. It enforces and guarantees to have a value forLogPrefix (LogPrefix uses to obtain the detail of the source class, which the exception has occurred) for every subclass, before they invoke a method to log an error.The method named LogError is protected, hence exposed to all subclasses. You are not allowed or rather you cannot make it public, as any class, without inheriting the LoggerBase cannot use it meaningfully.Let’s find out why the property named IsThisLogError is public. It may be important/ useful for other associated classes of an inherited class to know whether the associated member logs its errors or not.

Apart from these you can also have virtual methods defined in an abstract class. The virtual method may have its default implementation, where a subclass can override it when required.

All and all, the important factor here is that all OOP concepts should be used carefully with reasons, you should be able to logically explain, why you make a property a public or a field a private or a class an abstract. Additionally, when architecting frameworks, the OOP concepts can be used to forcefully guide the system to be developed in the way framework architect’s wanted it to be architected initially.4.12. What is an Interface?In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently. Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme.

Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the

Page 5: What is OOP

subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.

The sample below will provide an interface for our LoggerBase abstract class. Collapse | Copy Code

 Collapse | Copy Code

public interface ILogger{ bool IsThisLogError { get; }}

4.13. What is the difference between a Class and an Interface?In .NET/ C#, a class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface, an object of such class can be encapsulated inside an interface.If MyLogger is a class, which implements ILogger, there we can write

 Collapse | Copy Code

 Collapse | Copy Code

ILogger log = new MyLogger();

A class and an interface are two different types (conceptually). Theoretically a class emphasis the idea of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). The two poses a clear separation from one to another. Therefore it is very difficult or rather impossible to have an effective meaningful comparison between the two, but it is very useful and also meaningful to have a comparison between an interface and an abstract class.4.14. What is the difference between an Interface and an Abstract class?There are quite a big difference between an interface and an abstract class, even though both look similar.

Interface definition begins with a keyword interface so it is of type interface Abstract classes are declared with the abstract keyword so it is of type class Interface has no implementation, but they have to be implemented. Abstract class’s methods can have implementations and they have to be extended. Interfaces can only have method declaration (implicitly public and abstract) and

properties (implicitly public static) Abstract class’s methods can’t have implementation only when declared abstract. Interface can inherit more than one interfaces Abstract class can implement more than one interfaces, but can inherit only one class Abstract class must override all abstract method and may override virtual methods Interface can be used when the implementation is changing Abstract class can be used to provide some default behavior for a base class. Interface makes implementation interchangeable Interface increase security by hiding the implementation Abstract class can be used when implementing framework Abstract classes are an excellent way to create planned inheritance hierarchies and also

to use as non-leaf classes in class hierarchies.

Page 6: What is OOP

Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class can be used to provide the default implementation of the services and all mandatory modules such as event logging and message handling etc. This approach allows the developers to develop the application within the guided help provided by the framework.

However, in practice when you come across with some application-specific functionality that only your application can perform, such as startup and shutdown tasks etc. The abstract base class can declare virtual shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, it can execute the method defined by the child class.

What is Inheritance?

Inheritance (C# Programming Guide)Other Versions

14 out of 18 rated this helpful - Rate this topic

Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

 Note

Structs do not support inheritance, but they can implement interfaces. For more information, see Interfaces (C# Programming Guide).

Conceptually, a derived class is a specialization of the base class. For example, if you have a base class Animal, you might have one derived class that is named Mammal and another derived class that is named Reptile. A Mammal is anAnimal, and a Reptile is an Animal, but each derived class represents different specializations of the base class.

Page 7: What is OOP

When you define a class to derive from another class, the derived class implicitly gains all the members of the base class, except for its constructors and destructors. The derived class can thereby reuse the code in the base class without having to re-implement it. In the derived class, you can add more members. In this manner, the derived class extends the functionality of the base class.The following illustration shows a class WorkItem that represents an item of work in some business process. Like all classes, it derives from System.Object and inherits all its methods. WorkItem adds five members of its own. These include a constructor, because constructors are not inherited. Class ChangeRequest inherits from WorkItem and represents a particular kind of work item. ChangeRequest adds two more members to the members that it inherits from WorkItem and from Object. It must add its own constructor, and it also adds originalItemID. PropertyoriginalItemID enables the ChangeRequest instance to be associated with the original WorkItem to which the change request applies.Class inheritance

The following example shows how the class relationships demonstrated in the previous illustration are expressed in C#. The example also shows how WorkItem overrides the virtual method Object.ToString, and how theChangeRequest class inherits the WorkItem implementation of the method.C#

// WorkItem implicitly inherits from the Object class. public class WorkItem{ // Static field currentID stores the job ID of the last WorkItem that  // has been created.  private static int currentID;

//Properties.  protected int ID { get; set; }

Page 8: What is OOP

protected string Title { get; set; } protected string Description { get; set; } protected TimeSpan jobLength { get; set; }

// Default constructor. If a derived class does not invoke a base-  // class constructor explicitly, the default constructor is called  // implicitly.   public WorkItem() { ID = 0; Title = "Default title"; Description = "Default description."; jobLength = new TimeSpan(); }

// Instance constructor that has three parameters.  public WorkItem(string title, string desc, TimeSpan joblen) { this.ID = GetNextID(); this.Title = title; this.Description = desc; this.jobLength = joblen; }

// Static constructor to initialize the static member, currentID. This  // constructor is called one time, automatically, before any instance  // of WorkItem or ChangeRequest is created, or currentID is referenced.  static WorkItem() { currentID = 0; }

protected int GetNextID() { // currentID is a static field. It is incremented each time a new  // instance of WorkItem is created.  return ++currentID; }

// Method Update enables you to update the title and job length of an  // existing WorkItem object.  public void Update(string title, TimeSpan joblen) { this.Title = title; this.jobLength = joblen; }

// Virtual method override of the ToString method that is inherited 

Page 9: What is OOP

// from System.Object.  public override string ToString() { return String.Format("{0} - {1}", this.ID, this.Title); }}

// ChangeRequest derives from WorkItem and adds a property (originalItemID)  // and two constructors. public class ChangeRequest : WorkItem{ protected int originalItemID { get; set; }

// Constructors. Because neither constructor calls a base-class   // constructor explicitly, the default constructor in the base class  // is called implicitly. The base class must contain a default   // constructor. 

// Default constructor for the derived class.  public ChangeRequest() { }

// Instance constructor that has four parameters.  public ChangeRequest(string title, string desc, TimeSpan jobLen, int originalID) { // The following properties and the GetNexID method are inherited   // from WorkItem.  this.ID = GetNextID(); this.Title = title; this.Description = desc; this.jobLength = jobLen;

// Property originalItemId is a member of ChangeRequest, but not   // of WorkItem.  this.originalItemID = originalID; }}

class Program{ static void Main() { // Create an instance of WorkItem by using the constructor in the   // base class that takes three arguments. WorkItem item = new WorkItem("Fix Bugs", "Fix all bugs in my code branch", new TimeSpan(3, 4, 0, 0));

// Create an instance of ChangeRequest by using the constructor in 

Page 10: What is OOP

// the derived class that takes four arguments. ChangeRequest change = new ChangeRequest("Change Base Class Design", "Add members to the class", new TimeSpan(4, 0, 0), 1);

// Use the ToString method defined in WorkItem. Console.WriteLine(item.ToString());

// Use the inherited Update method to change the title of the   // ChangeRequest object. change.Update("Change the Design of the Base Class", new TimeSpan(4, 0, 0));

// ChangeRequest inherits WorkItem's override of ToString. Console.WriteLine(change.ToString());

// Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }}/* Output: 1 - Fix Bugs 2 - Change the Design of the Base Class*/

Abstract and Virtual MethodsWhen a base class declares a method as virtual, a derived class can override the method with its own implementation. If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class. If a derived class is itself abstract, it inherits abstract members without implementing them. Abstract and virtual members are the basis for polymorphism, which is the second primary characteristic of object-oriented programming. For more information, see Polymorphism (C# Programming Guide).Abstract Base ClassesYou can declare a class as abstract if you want to prevent direct instantiation by using the new keyword. If you do this, the class can be used only if a new class is derived from it. An abstract class can contain one or more method signatures that themselves are declared as abstract. These signatures specify the parameters and return value but have no implementation (method body). An abstract class does not have to contain abstract members; however, if a class does contain an abstract member, the class itself must be declared as abstract. Derived classes that are not abstract themselves must provide the implementation for any abstract methods from an abstract base class. For more information, see Abstract and Sealed Classes and Class Members (C# Programming Guide).InterfacesAn interface is a reference type that is somewhat similar to an abstract base class that consists of only abstract members. When a class implements an interface, it must provide

Page 11: What is OOP

an implementation for all the members of the interface. A class can implement multiple interfaces even though it can derive from only a single direct base class.Interfaces are used to define specific capabilities for classes that do not necessarily have an "is a" relationship. For example, the System.IEquatable<T> interface can be implemented by any class or struct that has to enable client code to determine whether two objects of the type are equivalent (however the type defines equivalence).IEquatable<T> does not imply the same kind of "is a" relationship that exists between a base class and a derived class (for example, a Mammal is an Animal). For more information, see Interfaces (C# Programming Guide).Derived Class Access to Base Class MembersA derived class has access to the public, protected, internal, and protected internal members of a base class. Even though a derived class inherits the private members of a base class, it cannot access those members. However, all those private members are still present in the derived class and can do the same work they would do in the base class itself. For example, suppose that a protected base class method accesses a private field. That field has to be present in the derived class for the inherited base class method to work correctly.Preventing Further DerivationA class can prevent other classes from inheriting from it, or from any of its members, by declaring itself or the member as sealed. For more information, see Abstract and Sealed Classes and Class Members (C# Programming Guide).Derived Class Hiding of Base Class MembersA derived class can hide base class members by declaring members with the same name and signature. The newmodifier can be used to explicitly indicate that the member is not intended to be an override of the base member. The use of new is not required, but a compiler warning will be generated if new is not used. For more information, see Versioning with the Override and New Keywords (C# Programming Guide) and Knowing When to Use Override and New Keywords (C# Programming Guide).

What Is Inheritance?

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming

Page 12: What is OOP

language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

A hierarchy of bicycle classes.

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {

// new fields and methods defining // a mountain bike would go here

}

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

 Inheritance

Page 13: What is OOP

The language feature that is most often associated with object-oriented programming is inheritance. Inheritance is the ability to define a new class that is a modified version of a previously-defined class (including built-in classes).

The primary advantage of this feature is that you can add new methods or instance variables to an existing class without modifying the existing class. This is particularly useful for built-in classes, since you can't modify them even if you want to.

The reason inheritance is called "inheritance" is that the new class inherits all the instance variables and methods of the existing class. Extending this metaphor, the existing class is sometimes called the parent class.

The ability of a new class to be created, from an existing class by extending it, is called inheritance.

 Collapse | Copy Code

 Collapse | Copy Code

public class Exception{}

public class IOException : Exception{}

According to the above example the new class (IOException), which is called the derived class or subclass, inherits the members of an existing class (Exception), which is called the base class or super-class. The classIOException can extend the functionality of the class Exception by adding new types and methods and by overriding existing ones.

Just like abstraction is closely related with generalization, the inheritance is closely related with specialization. It is important to discuss those two concepts together with generalization to better understand and to reduce the complexity.

Page 14: What is OOP

One of the most important relationships among objects in the real world is specialization, which can be described as the “is-a” relationship. When we say that a dog is a mammal, we mean that the dog is a specialized kind of mammal. It has all the characteristics of any mammal (it bears live young, nurses with milk, has hair), but it specializes these characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As such, we expect it to share certain characteristics with the dog that are generalized in Mammal, but to differ in those characteristics that are specialized in cats.

The specialization and generalization relationships are both reciprocal and hierarchical. Specialization is just the other side of the generalization coin: Mammal generalizes what is common between dogs and cats, and dogs and cats specialize mammals to their own specific subtypes.

Similarly, as an example you can say that both IOException and SecurityException are of typeException. They have all characteristics and behaviors of an Exception, That mean the IOException is a specialized kind of Exception. A SecurityException is also an Exception. As such, we expect it to share certain characteristic with IOException that are generalized in Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In other words, Exception generalizes the shared characteristics of both IOException and SecurityException, while IOException and SecurityException specialize with their characteristics and behaviors.In OOP, the specialization relationship is implemented using the principle called inheritance. This is the most common and most natural and widely accepted way of implement this relationship.4.17. What is Polymorphism?

polymorphism (C# Programming Guide)Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:

At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.

Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.

Virtual methods enable you to work with groups of related objects in a uniform way. For example, suppose you have a drawing application that enables a user to create various kinds of shapes on a drawing surface. You do not know at compile time which specific types

Page 15: What is OOP

of shapes the user will create. However, the application has to keep track of all the various types of shapes that are created, and it has to update them in response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:

1. Create a class hierarchy in which each specific shape class derives from a common base class.

2. Use a virtual method to invoke the appropriate method on any derived class through a single call to the base class method.

First, create a base class called Shape, and derived classes such as Rectangle, Circle, and Triangle. Give theShape class a virtual method called Draw, and override it in each derived class to draw the particular shape that the class represents. Create a List<Shape> object and add a Circle, Triangle and Rectangle to it. To update the drawing surface, use a foreach loop to iterate through the list and call the Draw method on each Shape object in the list. Even though each object in the list has a declared type of Shape, it is the run-time type (the overridden version of the method in each derived class) that will be invoked.C#

public class Shape{ // A few example members  public int X { get; private set; } public int Y { get; private set; } public int Height { get; set; } public int Width { get; set; }

// Virtual method  public virtual void Draw() { Console.WriteLine("Performing base class drawing tasks"); }}

class Circle : Shape{ public override void Draw() { // Code to draw a circle... Console.WriteLine("Drawing a circle"); base.Draw(); }}class Rectangle : Shape{ public override void Draw() { // Code to draw a rectangle... Console.WriteLine("Drawing a rectangle"); base.Draw(); }

Page 16: What is OOP

}class Triangle : Shape{ public override void Draw() { // Code to draw a triangle... Console.WriteLine("Drawing a triangle"); base.Draw(); }}

class Program{ static void Main(string[] args) { // Polymorphism at work #1: a Rectangle, Triangle and Circle  // can all be used whereever a Shape is expected. No cast is  // required because an implicit conversion exists from a derived   // class to its base class. System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>(); shapes.Add(new Rectangle()); shapes.Add(new Triangle()); shapes.Add(new Circle());

// Polymorphism at work #2: the virtual method Draw is  // invoked on each of the derived classes, not the base class.  foreach (Shape s in shapes) { s.Draw(); }

// Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }

}

/* Output: Drawing a rectangle Performing base class drawing tasks Drawing a triangle Performing base class drawing tasks Drawing a circle Performing base class drawing tasks */In C#, every type is polymorphic because all types, including user-defined types, inherit from Object.

Page 17: What is OOP

Polymorphism OverviewVirtual MembersWhen a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. The designer of the derived class can choose whether to

override virtual members in the base class, inherit the closest base class method without overriding it define new non-virtual implementation of those members that hide the base class

implementationsA derived class can override a base class member only if the base class member is declared as virtual orabstract. The derived member must use the override keyword to explicitly indicate that the method is intended to participate in virtual invocation. The following code provides an example:C#

public class BaseClass{ public virtual void DoWork() { } public virtual int WorkProperty { get { return 0; } }}public class DerivedClass : BaseClass{ public override void DoWork() { } public override int WorkProperty { get { return 0; } }}Fields cannot be virtual; only methods, properties, events and indexers can be virtual. When a derived class overrides a virtual member, that member is called even when an instance of that class is being accessed as an instance of the base class. The following code provides an example:C#

DerivedClass B = new DerivedClass();B.DoWork(); // Calls the new method.

BaseClass A = (BaseClass)B;A.DoWork(); // Also calls the new method.Virtual methods and properties enable derived classes to extend a base class without needing to use the base class implementation of a method. For more information, see Versioning with the Override and New Keywords (C# Programming Guide). An interface provides another way to define a method or set of methods whose implementation is left to derived classes. For more information, see Interfaces (C# Programming Guide).Hiding Base Class Members with New Members

Page 18: What is OOP

If you want your derived member to have the same name as a member in a base class, but you do not want it to participate in virtual invocation, you can use the new keyword. The new keyword is put before the return type of a class member that is being replaced. The following code provides an example:C#

public class BaseClass{ public void DoWork() { WorkField++; } public int WorkField; public int WorkProperty { get { return 0; } }}

public class DerivedClass : BaseClass{ public new void DoWork() { WorkField++; } public new int WorkField; public new int WorkProperty { get { return 0; } }}Hidden base class members can still be accessed from client code by casting the instance of the derived class to an instance of the base class. For example:C#

DerivedClass B = new DerivedClass();B.DoWork(); // Calls the new method.

BaseClass A = (BaseClass)B;A.DoWork(); // Calls the old method.

Preventing Derived Classes from Overriding Virtual MembersVirtual members remain virtual indefinitely, regardless of how many classes have been declared between the virtual member and the class that originally declared it. If class A declares a virtual member, and class B derives from A, and class C derives from B, class C inherits the virtual member, and has the option to override it, regardless of whether class B declared an override for that member. The following code provides an example:C#

public class A{ public virtual void DoWork() { }}public class B : A

Page 19: What is OOP

{ public override void DoWork() { }}A derived class can stop virtual inheritance by declaring an override as sealed. This requires putting the sealedkeyword before the override keyword in the class member declaration. The following code provides an example:C#

public class C : B{ public sealed override void DoWork() { }}In the previous example, the method DoWork is no longer virtual to any class derived from C. It is still virtual for instances of C, even if they are cast to type B or type A. Sealed methods can be replaced by derived classes by using the new keyword, as the following example shows:C#

public class D : C{ public new void DoWork() { }}In this case, if DoWork is called on D using a variable of type D, the new DoWork is called. If a variable of type C, B, or A is used to access an instance of D, a call to DoWork will follow the rules of virtual inheritance, routing those calls to the implementation of DoWork on class C.Accessing Base Class Virtual Members from Derived ClassesA derived class that has replaced or overridden a method or property can still access the method or property on the base class using the base keyword. The following code provides an example:C#

public class Base{ public virtual void DoWork() {/*...*/ }}public class Derived : Base{ public override void DoWork() { //Perform Derived's work here  //...  // Call DoWork on base class  base.DoWork(); }}For more information, see base.

Page 20: What is OOP

 Note

It is recommended that virtual members use base to call the base class implementation of that member in their own implementation. Letting the base class behavior occur enables the derived class to concentrate on implementing behavior specific to the derived class. If the base class implementation is not called, it is up to the derived class to make their behavior compatible with the behavior of the base class.

Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts.

In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading, and method overriding,4.18. What is Method Overloading?Method overloading is the ability to define several methods all with the same name.

 Collapse | Copy Code

 Collapse | Copy Code

public class MyLogger{ public void LogError(Exception e) { // Implementation goes here }

public bool LogError(Exception e, string message) { // Implementation goes here }}

4.19. What is Operator Overloading?The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case ofpolymorphisms in which some or all of operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments.

 Collapse | Copy Code

 Collapse | Copy Code

Page 21: What is OOP

public class Complex{ private int real; public int Real { get { return real; } }

private int imaginary; public int Imaginary { get { return imaginary; } }

public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; }

public static Complex operator +(Complex c1, Complex c2) { return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); }}

I above example I have overloaded the plus operator for adding two complex numbers. There the two properties named Real and Imaginary has been declared exposing only the required “get” method, while the object’s constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class.

Static Classes and Static Class Members (C# Programming Guide)Visual Studio 2013

Other Versions

31 out of 34 rated this helpful - Rate this topic

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:C#

Page 22: What is OOP

UtilityClass.MethodA();A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Framework Class Library, the staticSystem.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class. That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example.double dub = -3.14;Console.WriteLine(Math.Abs(dub));Console.WriteLine(Math.Floor(dub));Console.WriteLine(Math.Round(Math.Abs(dub)));

// Output:// 3.14// -4// 3As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides. 

Note

To create a non-static class that allows only one instance of itself to be created, see Implementing Singleton in C#.

The following list provides the main features of a static class: Contains only static members. Cannot be instantiated. Is sealed. Cannot contain Instance Constructors.

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization. For more information, see Static Constructors (C# Programming Guide).

Page 23: What is OOP

ExampleHere is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius:C#

public static class TemperatureConverter { public static double CelsiusToFahrenheit(string temperatureCelsius) { // Convert argument to double for calculations.  double celsius = Double.Parse(temperatureCelsius);

// Convert Celsius to Fahrenheit.  double fahrenheit = (celsius * 9 / 5) + 32;

return fahrenheit; }

public static double FahrenheitToCelsius(string temperatureFahrenheit) { // Convert argument to double for calculations.  double fahrenheit = Double.Parse(temperatureFahrenheit);

// Convert Fahrenheit to Celsius.  double celsius = (fahrenheit - 32) * 5 / 9;

return celsius; } }

class TestTemperatureConverter { static void Main() { Console.WriteLine("Please select the convertor direction"); Console.WriteLine("1. From Celsius to Fahrenheit."); Console.WriteLine("2. From Fahrenheit to Celsius."); Console.Write(":");

string selection = Console.ReadLine(); double F, C = 0;

switch (selection) { case "1": Console.Write("Please enter the Celsius temperature: "); F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());

Page 24: What is OOP

Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F); break;

case "2": Console.Write("Please enter the Fahrenheit temperature: "); C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine()); Console.WriteLine("Temperature in Celsius: {0:F2}", C); break;

default: Console.WriteLine("Please select a convertor."); break; }

// Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Example Output: Please select the convertor direction 1. From Celsius to Fahrenheit. 2. From Fahrenheit to Celsius. :2 Please enter the Fahrenheit temperature: 20 Temperature in Celsius: -6.67 Press any key to exit. */

Static MembersA non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the sameClassName.MemberName notation that is used for static fields. No object instance is required.

Page 25: What is OOP

C# does not support static local variables (variables that are declared in method scope).You declare static class members by using the static keyword before the return type of the member, as shown in the following example:C#

public class Automobile{ public static int NumberOfWheels = 4; public static int SizeOfGasTank { get { return 15; } } public static void Drive() { } public static event EventType RunOutOfGas;

// Other non-static fields and properties...}Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member, as shown in the following example:C#

Automobile.Drive();int i = Automobile.NumberOfWheels;If your class contains static fields, provide a static constructor that initializes them when the class is loaded.A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.