Flipkart Search

Search This Blog

Thursday, March 26, 2009

Object Oriented Programming

Object Oriented Programming

Object-oriented programming is a programming paradigm that uses abstraction (in the form of classes and objects) to create models based on the real world environment. An object-oriented application uses a collection of objects, which communicate by passing messages to request services. Objects are capable of passing messages, receiving messages, and processing data. The aim of object-oriented programming is to try to increase the flexibility and maintainability of programs. Because programs created using an OO language are modular, they can be easier to develop, and simpler to understand after development.

Object-Oriented Programming vs. Procedural Programming

Programs are made up of modules, which are parts of a program that can be coded and tested separately, and then assembled to form a complete program. In procedural languages (i.e. C) these modules are procedures, where a procedure is a sequence of statements. In C for example, procedures are a sequence of imperative statements, such as assignments, tests, loops and invocations of sub procedures. These procedures are functions, which map arguments to return statements.

The design method used in procedural programming is called Top Down Design. This is where you start with a problem (procedure) and then systematically break the problem down into sub problems (sub procedures). This is called functional decomposition, which continues until a sub problem is straightforward enough to be solved by the corresponding sub procedure. The difficulties with this type of programming, is that software maintenance can be difficult and time consuming. When changes are made to the main procedure (top), those changes can cascade to the sub procedures of main, and the sub-sub procedures and so on, where the change may impact all procedures in the pyramid.

One alternative to procedural programming is object oriented programming. Object oriented programming is meant to address the difficulties with procedural programming. In object oriented programming, the main modules in a program are classes, rather than procedures. The object-oriented approach lets you create classes and objects that model real world objects.

Classes and Objects

A class is a collection of objects that have common properties, operations and behaviours. A class is a combination of state (data) and behaviour (methods). In object-oriented languages, a class is a data type, and objects are instances of that data type. In other words, classes are prototypes from which objects are created.

For example, we may design a class Human, which is a collection of all humans in the world. Humans have state, such as height, weight, and hair color. They also have behaviour, such as walking, talking, eating. All of the state and behaviour of a human is encapsulated (contained) within the class human.

An object is an instance of a class. Objects are units of abstraction. An object can communicate with other objects using messages. An object passes a message to another object, which results in the invocation of a method. Objects then perform the actions that are required to get a response from the system.

Real world objects all share two characteristics; they all have state and behaviour. One-way to begin thinking in an object oriented way is to identify the state and behaviour of real world objects. The complexity of objects can differ, some object have more states and more complex behaviours than other object. Compare the state and behaviour of a television to the states and behaviours of a car.

Software objects are conceptually similar to real world objects. An object stores its state in fields, and it exposes its behaviours through its methods.

A fundamental principle of object oriented programming is encapsulation; the hiding of an objects internal state and requiring all interaction to be performed using the objects methods. (Think of the classes used in VB.Net)

Classes and Objects Example - class Bicycle

There are many types of bicycles, but we can say that each bicycle was built from the same blueprint (or prototype) and each bicycle contains the same components. Your bicycle (a specific bicycle object) is an instance of a class of objects known as bicycles. Describe the state and behaviour of a bicycle.

Fields and Methods

Objects in a class have a number of shared properties/features/attributes. Fields are the variables contained in a class (encapsulated) that are used to represent these properties. For example, class Student may have an integer field to represent graduation year, or a String field to represent the student’s Last Name.

Before fields in an object can be assigned values, the object must first be constructed/created. In Java (as an example of an OO language) a special function called a constructor is used to create and initialize an instance of a class. The statement:

new Student();

creates an instance of the class Student, or in other words, a Student object. Each class has operations associated with it. Each Student object has a number of distinct behaviours, such as study, sleep, work, etcetera. The operations associated with a class, together with the attributes of a class are encapsulated within the class. These operations are called the methods of a class. Methods are functions that represent the operations associated with a particular class. Fields and methods are referred to as class members.

Encapsulation

Definition: the ability of an object to hide its data and methods from the rest of the world - one of the fundamental principles of OOP. Because objects encapsulate data and implementation, the user of an object can view the object as a black box that provides services. Instance variables and methods can be added, deleted, or changed, but as long as the services provided by the object remain the same, code that uses the object can continue to use it without being rewritten.

Coupling – the degree to which a module (class) depends on other classes. In a good design, you should try to minimize coupling. Classes should be self-contained units that have a low dependence on other classes, meaning understanding and using one class should not require an understanding of another. With low coupling a change in a module will not require changes in other modules.

Related to the concept of coupling is information hiding. Information hiding is the hiding of the implementation in a class or module that are most likely to change; this protects other parts of the program from change if the implementation is changed. Protecting an implementation involves providing a stable interface which other classes can use to access services provided by the class. Often encapsulation and information hiding are used interchangeably.

Example: Car and Driver

Cohesion – is the measure within a module (class) of how well the members work together to provide a specific piece of functionality. Cohesion is measured by how strongly related and focused the responsibilities of a single class are. In good design, the cohesion should be maximized. Cohesion is decreased if the methods of a class have little in common, or methods carry out many activities.

If cohesion is low, modules may be difficult to understand, maintenance is difficult, because change may affect many modules, and modules cannot be reused, because it is unlikely that another application will have a use for the random grouping of functionality.

Example: Oven that has built-in radio and alarm clock.

A well-designed system should maximize cohesion, and minimize coupling.

Inheritance

Multiple classes may share some of the same characteristics, and have things in common with one another, but also may have certain properties that make them different. Object oriented programming languages allow classes to inherit commonly used state and behaviour from other classes.

Classes in Java occur in inheritance hierarchies. These hierarchies consist of parent child relationships among the classes. Inheritance is used to specialize a parent class, but creating a child class (example). Inheritance also allows designers to combine features of classes in a common parent.

Example: Student

Benefits of Object Oriented Programming

1. Modularity: The source code for a class can be written and maintained independently of the source code for other classes. Once created, an object can be easily passed around inside the system.

2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

3. Code re-use: If a class already exists, you can use objects from that class in your program. This allows programmers to implement/test/debug complex, task-specific objects, which you can then use in your own code.

4. Easy Debugging: If a particular object turns out to be a problem, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

Summary of Object-Oriented Concepts

1. Everything is an object.

2. Computation is performed by objects communicating with each other, requesting that other objects perform actions. Objects communicate by sending and receiving messages. A message is a request for action, bundled with whatever arguments may be necessary to complete the tasks.

3. Each object has its own memory, which consists of other objects.

4. Every object is an instance of a class. A class simply represents a grouping of similar objects, such as Integers or lists.

5. The class is the repository for behaviour associated with an object. That is, that all objects that are instances of the same class can perform the same actions.

6. Classes are organized into a singly rooted tree structure, called the inheritance hierarchy. Memory and behaviour associated with instances of a class are automatically available to any class associated with a descendant in this tree structure.

Friday, March 20, 2009

Structure Vs Class


Visual Basic .NET unifies the syntax for structures and classes, with the result that both entities support most of the same features. However, there are also important differences between structures and classes.

Similarities

Structures and classes are similar in the following respects:

  • Both are container types, meaning that they contain other types as members.
  • Both have members, which can include constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Members of both can have individualized accessibilities. For example, one member can be declared Public and another Private.
  • Both can implement interfaces.
  • Both can have shared constructors, with or without parameters.
  • Both can expose a default property, provided that property takes at least one argument.
  • Both can declare and raise events, and both can declare delegates.

Differences

Structures and classes differ in the following particulars:

  • Structures are value types; classes are reference types.
  • Structures use stack allocation; classes use heap allocation.
  • All structure members are Public by default; class variables and constants are Private by default, while other class members are Public by default. This behavior for class members provides compatibility with the Visual Basic 6.0 system of defaults.
  • A structure must have at least one nonshared variable or event member; a class can be completely empty.
  • Structure members cannot be declared as Protected; class members can.
  • A structure procedure can handle events only if it is a Shared Sub procedure, and only by means of the AddHandler statement; any class procedure can handle events, using either the Handles keyword or the AddHandler statement.
  • Structure variable declarations cannot specify initializers, the New keyword, or initial sizes for arrays; class variable declarations can.
  • Structures implicitly inherit from the ValueType class and cannot inherit from any other type; classes can inherit from any class or classes other than ValueType.
  • Structures are not inheritable; classes are.
  • Structures are never terminated, so the common language runtime (CLR) never calls the Finalize method on any structure; classes are terminated by the garbage collector, which calls Finalize on a class when it detects there are no active references remaining.
  • A structure does not require a constructor; a class does.
  • Structures can have nonshared constructors only if they take parameters; classes can have them with or without parameters.

Every structure has an implicit public constructor without parameters. This constructor initializes all the structure's data members to their default values. You cannot redefine this behavior.

Instances and Variables

Because structures are value types, each structure variable is permanently bound to an individual structure instance. But classes are reference types, and an object variable can refer to various class instances. This distinction affects your usage of structures and classes in the following ways:

  • A structure variable implicitly includes an initialization of the members using the structure's parameterless constructor. Therefore, Dim S As Struct1 is equivalent to Dim S As Struct1 = New Struct1().
  • When you assign one structure variable to another, or pass a structure instance to a procedure argument, the current values of all the variable members are copied to the new structure. When you assign one object variable to another, or pass an object variable to a procedure, only the reference pointer is copied.
  • You can assign the value Nothing to a structure variable, but the instance continues to be associated with the variable. You can still call its methods and access its data members, although variable members are reinitialized by the assignment. In contrast, if you set an object variable to Nothing, you dissociate it from any class instance, and you cannot access any members through the variable until you assign another instance to it.
  • An object variable can have different class instances assigned to it at different times, and several object variables can refer to the same class instance at the same time. Changes you make to the values of class members affect those members when accessed through another variable pointing to the same instance. Structure members, however, are isolated within their own instance. Changes to their values are not reflected in any other structure variables, even in other instances of the same Structure declaration.
  • Equality testing of two structures must be performed with a member-by-member test. Two object variables can be compared using the Equals method. Equals indicates whether the two variables point to the same instance.

What is the difference between Object Oriented Programming and Procedural Programming?


Procedural programming creates a step by step program that guides the application through a sequence of instructions. Each instruction is executed in order. Procedural programming also focuses on the idea that all algorithms are executed with functions and data that the programmer has access to and is able to change. Object-Oriented programming is much more similar to the way the real world works; it is analogous to the human brain. Each program is made up of many entities called objects. Objects become the fundamental units and have behavior, or a specific purpose, associated with them. Objects cannot directly access another object’s data. Instead, a message must be sent requesting the data, just like people must ask one another for information; we cannot see inside each other’s heads. Benefits of Object-Oriented programming include:

  • ability to simulate real-world event much more effectively
  • code is reusable thus less code may have to be written
  • data becomes active
  • better able to create GUI (graphical user interface) applications
  • programmers are able to reach their goals faster
  • Programmers are able to produce faster, more accurate and better-written applications (in the case of a veteran programmer, by a factor of as much as 20 times compared with a procedural program).

Web Links for Object Oriented Programming

http://ignou.ac.in/MASTERS(II).doc

the best tutorial(*****)
http://www.jgcampbell.com/oopcpp/html/node2.html

http://net.pku.edu.cn/~course/cs101/resource/CppHowToProgram/5e/html/ch01.html

jg.campbell@ntlworld.com

http://debuggable.com/posts/introduction-to-test-driven-development-tdd-part-1:480f4dfd-e8f4-4a82-923c-4625cbdd56cb
http://debuggable.com/posts/introduction-to-test-driven-development-tdd-part-2:480f4dfd-b3e4-4f84-9399-4084cbdd56cb
http://debuggable.com/posts/problems-with-repeatitive-source-code-or-better-dont-repeat-yourself:480f4dfd-ac70-4f1b-907b-4eb4cbdd56cb
http://debuggable.com/posts/the-various-kinds-of-design-patterns:480f4dfe-eab0-49ad-b2b0-4575cbdd56cb
http://www.javaworld.com/javaworld/jw-07-1999/jw-07-toolbox.html?page=1

http://www.programmersheaven.com/2/Art_ObjBasedSystems

http://wiki.tcl.tk/13398

http://www.archwing.com/technet/technet_OO.html

http://www.catalysoft.com/articles/simulatingOO.html

http://www.ctp.bilkent.edu.tr/~russell/java/LectureNotes/1_OOConcepts.htm

http://www.scribd.com/doc/7281196/Ooc-Slides

http://www.codeproject.com/KB/books/OOP_Polymorphism.aspx

http://mycplus.com/source-code/c-source-code/great-librarian-2001/

http://dir.yahoo.com/Computers_and_Internet/Programming_and_Development/Methodologies/Object_Oriented_Programming/

http://mycplus.com/category/source-code/c-source-code/

http://mycplus.com/category/source-code/cplusplus-source-code/

http://mycplus.com/tutorials/csharp-programming-tutorials/microsoft-net/

http://www.research.att.com/~bs/whatis.pdf

http://www.owlnet.rice.edu/~mech517/Books/oop3.pdf

http://www.restafari.org/object-oriented-sheep-running-in-ruby-shoes.html

http://www.startvbdotnet.com/oop/default.aspx

http://gd.tuwien.ac.at/languages/c/c++oop-pmueller/node3.html#SECTION00350000000000000000

http://www.codinghorror.com/blog/archives/000801.html

http://www.tutorialized.com/tutorial/bject-Oriented-Programming-Vs-Procedure-oriented-programming---C%2B%2B/27666

http://www.indianjournals.com/ijor.aspx?target=ijor:glogift2k5&volume=1&issue=1&article=chap037&type=pdf

http://objectmix.com/c/784333-procedural-vs-object-oriented-programming-methodology.html

http://bpsharma.in/StructureVsClass.htm

http://wiki.answers.com/Q/Difference_between_object_oriented_and_non_object_oriented_languages

http://www.astahost.com/info.php/Tutorial-Lesson-4-Object-Oriented-Programming_t15397.html

http://en.wikipedia.org/wiki/C%2B%2B_structures_and_classes

http://forums.devshed.com/c-programming-42/declaring-function-in-structure-in-c-545529.html

Thursday, March 19, 2009

web links

http://objc.toodarkpark.net/oop.html

http://www.softwaredesign.com/objects.html

Wednesday, March 18, 2009

Overloading And Overriding

Q: Method Overloading ?

Ans:

Method overloading means having two or more methods with the same name but different signatures in the same scope. These two methods may exist in the same class or anoter one in base class and another in derived class.

class Person

{

private String firstName;

private String lastName;

Person()

{

this.firstName = "";

this.lastName = "";

}

Person(String FirstName)

{

this.firstName = FirstName;

this.lastName = "";

}

Person(String FirstName, String LastName)

{

this.firstName = FirstName;

this.lastName = LastName;

}

}

Calling Overloaded Methods.

Person(); // as a constructor and call method without parameter

Person(userFirstName); // as a constructor and call method with one parameter(like User's first Name)

Person(userFirstName,userLastName); // as a constructor and call method with one parameter(like User's first Name)

When to use Method Overloading?

Generally, you should consider overloading a method when you have required same reason that take different signatures, but conceptually do the same thing.

-----------------------------------------------------------------------------------------

Q: Method Overriding?

Ans:

Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class.

Overriding methods

Overriding method definitions

In a derived class, if you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the base class, this new definition replaces the old definition of the method.

Explanation

A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding. The following example demonstrates method overriding.

Step 1

In this example we will define a base class called Circle

class Circle
{

//declaring the instance variable

protected double radius;

public Circle(double radius)
{
this.radius = radius;
}

// other method definitions here

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

}//this method returns the area of the circle

}// end of class circle

When the getArea method is invoked from an instance of the Circle class, the method returns the area of the circle.

Step 2

The next step is to define a subclass to override the getArea() method in the Circle class. The derived class will be the Cylinder class. The getArea() method in the Circle class computes the area of a circle, while the getArea method in the Cylinder class computes the surface area of a cylinder.

The Cylinder class is defined below.

class Cylinder extends Circle
{

//declaring the instance variable

protected double length;

public Cylinder(double radius, double length)
{
super(radius);
this.length = length;
}

// other method definitions here

public double getArea()
{
// method overriden here
return 2*super.getArea()+2*Math.PI*radius*length;
}//this method returns the cylinder surface area

}// end of class Cylinder

When the overriden method (getArea) is invoked for an object of the Cylinder class, the new definition of the method is called and not the old definition from the superclass(Circle).

Example code

This is the code to instantiate the above two classes

Circle myCircle;
myCircle = new Circle(1.20);
Cylinder myCylinder;
myCylinder = new Cylinder(1.20,2.50);

Overloading Vs Overriding

overloading comes with in class for example :

Operator Overloading and Method overloading.

void Add( int i );
void Add( char c );

These two function declaration and definition in the same class is called method OVERLOADING.


overriding comes with two class ( base and drived class )

function in the base class is like

public virtual void Display();

function in the drived class is like

public override void Display();

this function overrides the base class .

I think you should know more on OOPs , Polimorphism , inheritance etc.



Author: Kamliesh Nadar 17 May 2005Member Level: GoldRating: Points: 2

Hi,

Overriding - same method names with same arguments and same return types associated in a class and its subclass.

Overloading - same method name with different arguments, may or may not be same return type written in the same class itself.

Example for overriding
Clas A
{
Virtual void hi(int a)
{
}
}

Class B:A
{
public overrid void hi(int a)
{

}
}

Example for Over loading

Class A
{
class a()

{

}
class a(int a)
{
}
}

Regards,



Author: M.Ravi Kishore 18 May 2005Member Level: SilverRating: Points: 2

OverLoading means one name many forms .its functionallty changes corresponding to the objects
Overriding means its funcationality can be overrided.these can be done by using by using two keywords
1.overrideable
2.overrides
overriding take place with in the in_heritance. it is not possiable with in the class.
have u got it if not contact me(ravikim2001@yahoo.co.in)
ok bye.



Author: Maheswara Reddy 13 Jun 2007Member Level: BronzeRating: Points: 2

To begin with, overloading has been used before in other languages such as C++. If you have any C++ experience with overloading operators, this will be a snap. If not, don't worry; once you see a couple examples you'll be able to figure out where things are headed.

Method Overriding

Overriding in C# makes use of the "override" keyword. To override a method means to replace it with a new way of handling data. Here's an example of what I mean:

Say we have an object that contains data for a rectangle. Our object has accessors and a method for returning the area. This is our Rectangle object (refer to Accessors in C# for help understanding what this object does):


public class Rectangle
{
public int Width
{
set { width = value; }
get { return width; }
}

public int Height
{
set { height = value; }
get { return height; }
}

public int Area
{
get { return (width * height); }
}

int width, height;
}



Now for the overriding… The easiest, and most common, use of overriding is with the ToSting() method. ToString is a built-in method that returns a string, generally referring to some aspect of the object, to the calling statement. Let's look at the following Main() method used to call Rectangle:


class TestRectangle
{
public static void Main()
{
Rectangle myRect1 = new Rectangle();

myRect1.Width = 3;
myRect1.Height = 5;

Console.WriteLine("The area of a {0}, width={1} and height={2} is: {3}.",
myRect, myRect.Width, myRect.Height, myRect.Area);
}
}



The exact output for this is:
"The area of a Rectangle, width=3 and height=5 is: 15."

The first thing you should be asking is how the word "Rectangle" gets in there? This is where ToString() comes in. As with JAVA, when you try to reference an object as a string, it automatically calls ToString(); it'd be like calling myRect.ToString(). When we call myRect with Console.WriteLine(), it outputs myRect as a string. An un-overridden object will return the type of object it is, "Rectangle" in this case. Perhaps instead to returning "Rectangle," though, we want it to return "cool rectangle." To do this we must override ToString() in our object. Adding the following method to the Rectangle class will do this:


public override string ToString()
{
return "cool rectangle";
}



The only change between this method and any other method is the use of the override keyword. It's as simple as that. Now when the Main() method is run, the output will be:
"The area of a cool rectangle, width=3 and height=5 is: 15."

Overriding ToSting() is very useful if your class contains a list of information and you want to return it with some formatting already done. For example, you could create a string that formats a list of names for output similar to:

Name 1: Kevin
Name 2: Brittany
Name 3: Joseph
etc…

Then when your object (i.e. myNameList) is referenced as a string, it’ll return your formatted list of names.

Operator Overloading
OK, so overriding methods can be fun, but what about other things? Well let’s say we want to add two rectangles. Now the common way would be to add their areas, but maybe we want to add the lengths and the widths and find the new area. We could write a method that'd find this special area; but, if this is the only way we plan on adding two rectangles, we can easily overload the '+' operator. Here are our two rectangles:


-- -- -- -- -- -- -- -- --
| | | |
| | | |
| | -- -- -- -- -- --
| |
-- -- --
Width: 3 Width: 6
Height: 4 Height: 2
Area: 12 Area: 12



Doing our new form of adding, the resulting rectangle should be:


-- -- -- -- -- -- -- -- --
| | |
| |_________________|
| |__|__|__| |
|________|__|__|__| |
| | |
| | |
-- -- -- -- -- -- -- -- --
Width: 9
Height: 6
Area: 54



To begin, let's create the method header. We know we want to return a new rectangle with the new dimensions. To simplify things, we're going to take in the two small rectangles and return the composite rectangle. Our header will look as follows:


public static Rectangle operator + (Rectangle nRect1, Rectangle nRect2);



You should be able to figure out what each part is doing here. The return type is a Rectangle, the operator keyword tells that we're overloading an operator, and the operator is the + symbol; the method is also taking in our two small rectangles. Here's what the entire method might look like:


public static Rectangle operator + (Rectangle nRect1, Rectangle nRect2)
{
Rectangle retRect = new Rectangle();

retRect.Width = nRect1.Width + nRect2.Width;
retRect.Height = nRect1.Height + nRect2.Height;

return retRect;
}



I could have addressed width and height directly, but it is safer to use the accessors because I may have performed some special operation on the data with them (in this case I didn't so it wouldn't matter either way).

Putting the new Rectangle class together along with a testing Main() method, we'd have:


using System;

namespace Overloading
{
class TestRectangle
{
public static void Main()
{
Rectangle myRect1 = new Rectangle();
Rectangle myRect2 = new Rectangle();
Rectangle myRect3 = new Rectangle();

myRect1.Width = 3;
myRect1.Height = 4;

myRect2.Width = 6;
myRect2.Height = 2;

myRect3 = myRect1 + myRect2;

Console.WriteLine("The area of a {0}, width={1} and height={2} is: {3}.",
myRect1, myRect1.Width, myRect1.Height, myRect1.Area);
Console.WriteLine("The area of another {0}, width={1} and height={2} is: {3}.",
myRect2, myRect2.Width, myRect2.Height, myRect2.Area);
Console.WriteLine("The result of the {0}s added is: width={1}, height={2}, area={3}.",
myRect3, myRect3.Width, myRect3.Height, myRect3.Area);
}
}

public class Rectangle
{
public int Width
{
set { width = value; }
get { return width; }
}

public int Height
{
set { height = value; }
get { return height; }
}

public int Area
{
get { return (width * height); }
}

public static Rectangle operator + (Rectangle nRect1, Rectangle nRect2)
{
Rectangle retRect = new Rectangle();

retRect.Width = nRect1.Width + nRect2.Width;
retRect.Height = nRect1.Height + nRect2.Height;

return retRect;
}

public override string ToString()
{
return "cool rectangle";
}

int width, height;
}
}

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

using System;
namespace Polymorphism
{
class A
{
public virtual void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public override void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "B::Foo()"
}
}
}

Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}

Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:

class A
{
public void Foo() {}
}

class B : A
{
public virtual new void Foo() {}
}


A class C can now declare a method Foo() that either overrides or hides Foo() from class B:

class C : B
{
public override void Foo() {}
// or
public new void Foo() {}
}

Hope you can get complete idea.
Still you will get doubts on the same ,don't hesitate to send mail to Maheshreddy245@gmail.com

Cheers
Mahesh Reddy



Author: shivshankeryadav 13 Mar 2008Member Level: BronzeRating: Points: 2

Hi...
Overloading and overriding both are concerned with the oops. Overloading means same method name but different parameters, call depends upon the no. and types of parameters. While Overriding means changing the body of the method in the derived class.

Let me explain...
Suppose there is a class A having a method named alert(), and a derived class named B, now when we create an object of and call the method, the method os class A is called always. Now we want that we call the same method but behave differently, then we override it in the derived class. for this we use virtual keyword in the base class and override in the derived class to override and then change the body as per our need.

now when we create an object and call the method, the method of derived class will be caleed instead of the base class, This is the overriding.



Author: chakravarthy 17 Apr 2008Member Level: SilverRating: Points: 2

OverLoading is different from Overriding

Overloading comes when you define two methods or morethan two methods with the same name in the same class with different signature.

Overriding comes when you redefine a method that has already been defined in a parent class with ther same signature.

Overloading is resolved at compiletime
Overriding is resolved at runtime.

simply we can tell like Overloading deals with multiple methods in the same class with the same name but different signature
where as overriding deals with two methods one is in parent class and another one is in derived class that have the same signature, means when you override, you change the method behaviour for a child class.


Here is the Example
Public class A{
int a,b;
public int add(){
return a+b;
}
public float add(){
return a+b;
}
public int add(int i, int j){
int i+j;
}
}
in the above example shows add method is having the different signature first method doesn't take any parameter second methos returns the different floating value and thord one takes 2 parameters
in Overriding
public class BaseHide {
public BaseHide() {

}

public virtual string OverrideMe() {
return "Base Class Override Me";
}
}
public class DerivedHide : BaseHide {
public DerivedHide() {

}
public override string OverrideMe() {
return "Derived Class Override Me";
}
}
class Program {
static void Main(string[] args) {

DerivedHide derivedHideOverrideObject = new DerivedHide();
Console.WriteLine( derivedHideOverrideObject.OverrideMe());

BaseHide baseHideOverrideObject = new DerivedHide();
Console.WriteLine( baseHideOverrideObject.OverrideMe()); }
}



Author: asdf 12 Aug 2008Member Level: SilverRating: Points: 0

• Overloading
Having another method in the same name within the class. But arguments will be vary


• Overriding
Change the behaviour of the method of the derived class by the key word Override. But base class the same method should be used the keyword Virtual.



Author: Sridhar R 20 Feb 2009Member Level: DiamondRating: Points: 4

Overloading..
1.Same name but there are different definitions and parameters..
2.Here, the definitions are extented.
3.Seperate methods share the same name.
4.It is mainly for operators.
5.It must have different method signatures.

Overriding.
1.Here replacement of methods.
2.It is used in inheritance.
3.subclass methods replaces the superclass.
4.It is mainly for functions.
5.It must have same signature

Verify these links,

http://www.allinterview.com/showanswers/241.html
http://wiki.answers.com/Q/Difference_between_overriding_and_overloading
http://en.allexperts.com/q/C-1040/Difference-Overriding-Overloading.htm
http://answers.yahoo.com/question/index?qid=20060924201736AA1Qs5C

Nothing is illegal, Until You Get Caught

Polymorphism in C#

Creating Polymorphic Types

Because a ListBox is a Windowand aButtonis a Window, you expect to be able to use either of these types in situations that call for a Window. For example, a form might want to keep a collection of all the derived instances of Window it manages (buttons, lists, and so on), so that when the form is opened, it can tell each of its Windows to draw itself. For this operation, the form does not want to know which elements areListBoxes and which areButtons; it just wants to tick through its collection and tell each one to “draw.” In short, the form wants to treat all its Window objects polymorphically.

You implement polymorphism in two steps:

  1. Create a base class with virtual methods.
  2. Create derived classes that override the behavior of the base class’s virtual methods.

To create a method in a base class that supports polymorphism, mark the method asvirtual. For example, to indicate that the methodDrawWindow()of class Window in Example 11-1 is polymorphic, add the keywordvirtual to its declaration, as follows:

public virtual void DrawWindow()

Each derived class is free to inherit and use the base class’sDrawWindow()method as is or to implement its own version ofDrawWindow(). If a derived class does override theDrawWindow()method, that overridden version will be invoked for each instance of the derived class. You override the base class virtual method by using the keyword override in the derived class method definition, and then add the modified code for that overridden method.

Example 11-2 shows how to override virtual methods.

Example 11-2. Virtual methods

using System;

public class Window
{
// constructor takes two integers to
// fix location on the console
public Window( int top, int left )
{
this.top = top;
this.left = left;
}

// simulates drawing the window
public virtual void DrawWindow()
{
Console.WriteLine( "Window: drawing Window at {0}, {1}",
top, left );
}

// these members are protected and thus visible
// to derived class methods. We'll examine this
// later in the chapter. (Typically, these would be private
// and wrapped in protected properties, but the current approach
// keeps the example simpler.)
protected int top;
protected int left;

} // end Window

// ListBox derives from Window
public class ListBox : Window
{
// constructor adds a parameter
// and calls the base constructor
public ListBox(
int top,
int left,
string contents ) : base( top, left )
{
listBoxContents = contents;
}

// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow()
{
base.DrawWindow(); // invoke the base method
Console.WriteLine( "Writing string to the listbox: {0}",
listBoxContents );
}

private string listBoxContents; // new member variable
} // end ListBox

public class Button : Window
{
public Button(
int top,
int left ) : base( top, left )
{}

// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow()
{
Console.WriteLine( "Drawing a button at {0}, {1}\n",
top, left );
}
} // end Button

public class Tester
{
static void Main()
{
Window win = new Window( 1, 2 );
ListBox lb = new ListBox( 3, 4, "Stand alone list box" );
Button b = new Button( 5, 6 );
win.DrawWindow();
lb.DrawWindow();
b.DrawWindow();

Window[] winArray = new Window[3];
winArray[0] = new Window( 1, 2 );
winArray[1] = new ListBox( 3, 4, "List box in array" );
winArray[2] = new Button( 5, 6 );

for ( int i = 0; i <>

The output looks like this:

Window: drawing Window at 1, 2
Window: drawing Window at 3, 4
Writing string to the listbox: Stand alone list box
Drawing a button at 5, 6
Window: drawing Window at 1, 2
Window: drawing Window at 3, 4
Writing string to the listbox: List box in array
Drawing a button at 5, 6

In Example 11-2,ListBox derives from Window and implements its own version ofDrawWindow():

public override void DrawWindow()
{
base.DrawWindow(); // invoke the base method
Console.WriteLine ("Writing string to the listbox: {0}",
listBoxContents);
}

The keywordoverridetells the compiler that this class has intentionally overridden howDrawWindow()works. Similarly, you’ll overrideDrawWindow()in another class that derives fromWindow: theButton class.

In the body of the example, you create three objects: aWindow, aListBox, and aButton. Then you callDrawWindow()on each:

Window win = new Window(1,2);
ListBox lb = new ListBox(3,4,"Stand alone list box");
Button b = new Button(5,6);
win.DrawWindow();
lb.DrawWindow();
b.DrawWindow();

This works much as you might expect. The correctDrawWindow()method is called for each. So far, nothing polymorphic has been done (after all, you called theButtonversion ofDrawWindowon aButtonobject). The real magic starts when you create an array ofWindowobjects.

Because aListBoxis a Window, you are free to place aListBoxinto an array ofWindows. Similarly, you can add aButton to a collection ofWindows, because aButtonis a Window.

Window[] winArray = new Window[3];
winArray[0] = new Window(1,2);
winArray[1] = new ListBox(3,4,"List box in array");
winArray[2] = new Button(5,6);

The first line of code declares an array namedwinArray that will hold threeWindowobjects. The next three lines add newWindowobjects to the array. The first adds an object of typeWindow. The second adds an object of typeListBox(which is aWindow becauseListBoxderives fromWindow), and the third adds an object of typeButton, which is also a type ofWindow.

What happens when you callDrawWindow()on each of these objects?

for (int i = 0; i <>

This code usesias a counter variable. It callsDrawWindow()on each element in the array in turn. The valueiis evaluated each time through the loop, and that value is used as an index into the array.

All the compiler knows is that it has threeWindowobjects and that you’ve calledDrawWindow()on each. If you had not markedDrawWindow()asvirtual,Window’s originalDrawWindow()method would be called three times.

However, because you did markDrawWindow()as virtual, and because the derived classes override that method, when you callDrawWindow()on the array, the right thing happens for each object in the array. Specifically, the compiler determines the runtime type of the actual objects (aWindow, aListBox, and aButton) and calls the right method on each. This is the essence of polymorphism.

The runtime type of an object is the actual (derived) type. At compile time, you do not have to decide what kind of objects will be added to your collection, so long as they all derive from the declared type (in this case,Window). At runtime, the actual type is discovered and the right method is called. This allows you to pick the actual type of objects to add to the collection while the program is running.

Note that throughout this example, the overridden methods are marked with the keywordoverride:

public override void DrawWindow()

The compiler now knows to use the overridden method when treating these objects polymorphically. The compiler is responsible for tracking the real type of the object and for handling the late binding, so thatListBox.DrawWindow()is called when the Window reference really points to aListBox object.

In C#, the programmer’s decision to override a virtual method is made explicit with the override keyword. This helps you release new versions of your code; changes to the base class will not break existing code in the derived classes. The requirement to use theoverridekeyword helps prevent that problem.

Versioning with new and override

Here’s how: assume for a moment that Company A wrote theWindowbase class in Example 11-2. Suppose also that theListBoxandRadioButtonclasses were written by programmers from Company B using a purchased copy of the Company A Window class as a base. The programmers in Company B have little or no control over the design of the Window class, including future changes that Company A might choose to make.

Now suppose that one of the programmers for Company B decides to add aSort()method toListBox:

public class ListBox : Window
{
public virtual void Sort() {...}
}

This presents no problems until Company A, the author ofWindow, releases Version 2 of itsWindowclass, and the programmers in Company A also add aSort()method to their public classWindow:

public class Window
{
// ...
public virtual void Sort() {...}
}

In other object-oriented languages (such as C++), the new virtualSort()method inWindow would now act as a base virtual method for theSort()method inListBox, which is not what the developer ofListBoxintended.

C# prevents this confusion. In C#, avirtualfunction is always considered to be the root of virtual dispatch; that is, once C# finds a virtual method, it looks no further up the inheritance hierarchy. If a new virtualSort()function is introduced intoWindow, the runtime behavior of ListBoxis unchanged.

WhenListBoxis compiled again, however, the compiler generates a warning:

...\class1.cs(54,24): warning CS0114: 'ListBox.Sort()' hides
inherited member 'Window.Sort()'.
To make the current member override that implementation,
add the override keyword. Otherwise add the new keyword.

Never ignore warnings. Treat them as errors until you have satisfied yourself that you understand the warning and that it is not only innocuous but that there is nothing you can do to eliminate the warning. Your goal, (almost) always, is to compile warning-free code.

To remove the warning, the programmer must indicate what she intends.* She can mark theListBox Sort()methodnew to indicate that it is not an override of the virtual method in Window:

public class ListBox : Window
{
public new virtual void Sort() {...}

*In standard English, one uses “he” when the pronoun might refer either to a male or a female. Nonetheless, this assumption has such profound cultural implications, especially in the male-dominated programming profession, that I will use the term “she” for the unknown programmer from time to time. I apologize if this causes you to falter a bit when reading; consider it an opportunity to reflect on the linguistic implications of a patriarchal society.

This action removes the warning. If, on the other hand, the programmer does want to override the method in Window, she need only use theoverride keyword to make that intention explicit:

public class ListBox : Window
{
public override void Sort() {...}

To avoid this warning, it might be tempting to add thenewkeyword to all your virtual methods. This is a bad idea. Whennewappears in the code, it ought to document the versioning of code. It points a potential client to the base class to see what it is that you are intentionally not overriding. Usingnewscattershot undermines this documentation and reduces the utility of a warning that exists to help identify a real issue.

If the programmer now creates any new classes that derive fromListBox, those derived classes will inherit theSort()method fromListBox, not from the baseWindowclass.


Each type of Window has a different shape and appearance. Drop-down listboxes look very different from buttons. Clearly, every subclass of Window should implement its ownDrawWindow()method—but so far, nothing in the Window class enforces that they must do so. To require subclasses to implement a method of their base, you need to designate that method as abstract.

Abstract Classes

An abstract method has no implementation. It creates a method name and signature that must be implemented in all derived classes. Furthermore, making at least one method of any class abstract has the side effect of making the class abstract.

Abstract classes establish a base for derived classes, but it is not legal to instantiate an object of an abstract class. Once you declare a method to be abstract, you prohibit the creation of any instances of that class.

Thus, if you were to designateDrawWindow()as an abstract method in theWindowclass, theWindow class itself would become abstract. Then you could derive fromWindow, but you could not create anyWindowinstances. If theWindowclass is an abstraction, there is no such thing as a simpleWindowobject, only objects derived fromWindow.

MakingWindow.DrawWindow()abstract means that each class derived fromWindow would have to implement its ownDrawWindow()method. If the derived class failed to implement the abstract method, that derived class would also be abstract, and again no instances would be possible.


The Idea Behind Abstraction

Abstract classes should not just be an implementation trick; they should represent the idea of an abstraction that establishes a “contract” for all derived classes. In other words, abstract classes mandate the public methods of the classes that will implement the abstraction.

The idea of an abstract Window class ought to lay out the common characteristics and behaviors of all windows, even though you never intend to instantiate the abstraction Window itself.

The idea of an abstract class is implied in the word “abstract.” It serves to implement the abstraction “Window” that will be manifest in the various concrete instances of Window, such as browser window, frame, button, listbox, drop-down, and so forth. The abstract class establishes what a Window is, even though we never intend to create a “Window” per se. An alternative to usingabstractis to define an interface, as described in Chapter 13.


Designating a method as abstract is accomplished by placing theabstractkeyword at the beginning of the method definition:

abstract public void DrawWindow();

(Because the method can have no implementation, there are no braces, only a semicolon.)

If one or more methods are abstract, the class definition must also be markedabstract, as in the following:

abstract public class Window

Example 11-3 illustrates the creation of an abstract Window class and an abstractDrawWindow()method.

Example 11-3. Abstract methods

using System;

public abstract class Window
{
// constructor takes two integers to
// fix location on the console
public Window( int top, int left )
{
this.top = top;
this.left = left;
}

// simulates drawing the window
// notice: no implementation
public abstract void DrawWindow();

protected int top;
protected int left;
} // end class Window

// ListBox derives from Window
public class ListBox : Window
{
// constructor adds a parameter
public ListBox(
int top,
int left,
string contents ) : base( top, left ) // call base constructor
{

listBoxContents = contents;
}

// an overridden version implementing the
// abstract method
public override void DrawWindow()
{
Console.WriteLine( "Writing string to the listbox: {0}",
listBoxContents );
}
private string listBoxContents; // new member variable
} // end class ListBox

public class Button : Window
{
public Button(
int top,
int left ) : base( top, left ) { }

// implement the abstract method
public override void DrawWindow()
{
Console.WriteLine( "Drawing a button at {0}, {1}\n",
top, left );
}
} // end class Button

public class Tester
{
static void Main()
{
Window[] winArray = new Window[3];
winArray[0] = new ListBox( 1, 2, "First List Box" );
winArray[1] = new ListBox( 3, 4, "Second List Box" );
winArray[2] = new Button( 5, 6 );

for ( int i = 0; i < 3; i++ )
{
winArray[i].DrawWindow();
} // end for loop
} // end main
} // end class Tester

The output looks like this:

Writing string to the listbox: First List Box
Writing string to the listbox: Second List Box
Drawing a button at 5, 6

In Example 11-3, theWindowclass has been declared abstract and therefore cannot be instantiated. If you replace the first array member:

winArray[0] = new ListBox(1,2,"First List Box");

with this code:

winArray[0] = new Window(1,2);

the program generates the following error at compile time:

Cannot create an instance of the abstract class or interface 'Window'

You can instantiate theListBoxandButtonobjects because these classes override the abstract method, thus making the classes concrete (that is, not abstract).

Often an abstract class will include non-abstract methods. Typically, these will be marked virtual, providing the programmer who derives from your abstract class the choice of using the implementation provided in the abstract class, or overriding it. Once again, however, all abstract methods must, eventually, be overridden in order to make an instance of the (derived) class.

Sealed Classes

The opposite side of the design coin from abstract is sealed. In contrast to an abstract class, which is intended to be derived from and to provide a template for its subclasses to follow, a sealed class does not allow classes to derive from it at all. The sealed keyword placed before the class declaration precludes derivation. Classes are most often marked sealed to prevent accidental inheritance.

If you changed the declaration ofWindowin Example 11-3 fromabstracttosealed(eliminating theabstractkeyword from theDrawWindow()declaration as well), the program fails to compile. If you try to build this project, the compiler returns the following error message:

'ListBox' cannot inherit from sealed type 'Window'

among many other complaints (such as that you cannot create a new protected member in a sealed class).

Microsoft recommends using sealed when you know that you won’t need to create derived classes, and also when your class consists of nothing but static methods and properties.

All C# classes, of any type, ultimately derive from a single class: Object.Objectis the base class for all other classes.

The Root of All Classes: Object

A base class is the immediate “parent” of a derived class. A derived class can be the base to further derived classes, creating an inheritance tree or hierarchy. A root class is the topmost class in an inheritance hierarchy. In C#, the root class isObject. The nomenclature is a bit confusing until you imagine an upside-down tree, with the root on top and the derived classes below. Thus, the base class is considered to be “above” the derived class.

Object provides a number of methods that subclasses can override. These includeEquals(), which determines if two objects are the same, andToString(), which returns a string to represent the current object. Specifically,ToString()returns a string with the name of the class to which the object belongs. Table 11-1 summarizes the methods ofObject.

Table 11-1. The Object class

Method What it does
Equals() Evaluates whether two objects are equivalent
GetHashCode() Allows objects to provide their own hash function for use in collections (see Chapter 14)
GetType() Provides access to the Type object
ToString() Provides a string representation of the object
Finalize() Cleans up nonmemory resources; implemented by a destructor (finalizer)

In Example 11-4, theDog class overrides theToString()method inherited fromObject, to return the weight of theDog.

Example 11-4. Overriding ToString

using System;

public class Dog
{
private int weight;

// constructor
public Dog( int weight )
{
this.weight = weight;
}
// override Object.ToString
public override string ToString()
{
return weight.ToString();
}
}

public class Tester
{
static void Main()
{
int i = 5;
Console.WriteLine( "The value of i is: {0}", i.ToString() );

Dog milo = new Dog( 62 );
Console.WriteLine( "My dog Milo weighs {0} pounds", milo);
}
}

Output:
The value of i is: 5
My dog Milo weighs 62 pounds

Some classes (such asConsole) have methods that expect a string (such asWriteLine()). These methods will call theToString()method on your class if you’ve overridden the inheritedToString()method fromObject. This lets you pass aDog toConsole.WriteLine, and the correct information will display.

This example also takes advantage of the startling fact that intrinsic types (int,long, etc.) can also be treated as if they derive fromObject, and thus you can callToString()on anintvariable! CallingToString()on an intrinsic type returns a string representation of the variable’s value.

The documentation forObject.ToString()reveals its signature:

public virtual string ToString();

It is a public virtual method that returns a string and takes no parameters. All the built-in types, such asint, derive fromObjectand so can invokeObject’s methods.

TheConsole class’sWrite()andWriteLine()methods callToString()for you on objects that you pass in for display. Thus, by overridingToString()in theDogclass, you did not have to pass inmilo. ToString()but rather could just pass inmilo!

If you comment out the overridden function, the base method will be invoked. The base class default behavior is to return a string with the name of the class itself. Thus, the output would be changed to the meaningless:

My dog Milo weighs Dog pounds

Classes do not need to declare explicitly that they derive fromObject; the inheritance is implicit.


Boxing and Unboxing Types

Boxing and unboxing are the processes that enable value types (such as, integers) to be treated as reference types (objects). The value is “boxed” inside an Object and subsequently “unboxed” back to a value type. It is this process that allowed you to call theToString()method on the integer in Example 11-4.

Boxing Is Implicit

Boxing is an implicit conversion of a value type to the type Object. Boxing a value allocates an instance ofObjectand copies the value into the new object instance, as shown in Figure 11-4.


Figure 11-4. Boxing value types

Boxing is implicit when you provide a value type where a reference is expected. The runtime notices that you’ve provided a value type and silently boxes it within an object. You can, of course, first cast the value type to a reference type, as in the following:

int myIntegerValue = 5;
object myObject = myIntegerValue; // cast to an object
myObject.ToString();

This is not necessary, however, as the compiler boxes the value for you silently and with no action on your part:

int myIntegerValue = 5;
myIntegerValue.ToString(); // myIntegerValue is boxed

Unboxing Must Be Explicit

To return the boxed object back to a value type, you must explicitly unbox it. For the unboxing to succeed, the object being unboxed must really be of the type you indicate when you unbox it.

You should accomplish unboxing in two steps:

  1. Make sure the object instance is a boxed value of the given value type.
  2. Copy the value from the instance to the value-type variable.

Example 11-5 illustrates boxing and unboxing.

Example 11-5. Boxing and unboxing

using System;
public class UnboxingTest
{
public static void Main()
{
int myIntegerVariable = 123;

//Boxing
object myObjectVariable = myIntegerVariable;
Console.WriteLine( "myObjectVariable: {0}",
myObjectVariable.ToString() );

// unboxing (must be explicit)
int anotherIntegerVariable = (int)myObjectVariable;
Console.WriteLine( "anotherIntegerVariable: {0}",
anotherIntegerVariable );
}
}

Output:
myObjectVariable: 123 anotherIntegerVariable: 123

Figure 11-5 illustrates unboxing.

Example 11-5 creates an integermyIntegerVariableand implicitly boxes it when it is assigned to the objectmyObjectVariable; then, to exercise the newly boxed object, its value is displayed by callingToString().

The object is then explicitly unboxed and assigned to a new integer variable,anotherIntegerVariable, whose value is displayed to show that the value has been preserved.


Figure 11-5. Unboxing

Avoiding Boxing with Generics

The most common place that value types were boxed in C# 1.x was in collections that expected Objects. Now that C# supports generics, collections that hold integers need not box and unbox them, and that can increase performance when you have a very large collection.


Summary


  1. Specialization is described as the is-a relationship; the reverse of specialization is generalization.
  2. Specialization and generalization are reciprocal and hierarchical—that is, specialization is reciprocal to generalization, and each class can have any number of specialized derived classes but only one parent class that it specializes: thus creating a branching hierarchy.
  3. C# implements specialization through inheritance.
  4. The inherited class derives the public and protected characteristics and behaviors of the base class, and is free to add or modify its own characteristics and behaviors.
  5. You implement inheritance by adding a colon after the name of the derived class, followed by the name of its base class.
  6. A derived class can invoke the constructor of its base class by placing a colon after the parameter list and invoking the base class constructor with the keyword base.
  7. Classes, like members, can also use the access modifiers public,private, andprotected, though the vast majority of non-nested classes will be public.
  8. A method marked asvirtualin the base class can be overridden by derived classes if the derived classes use the keywordoverridein their method definition. This is the key to polymorphism in which you have a collection of references to a base class but each object is actually an instance of a derived class. When you call the virtual method on each derived object, the overridden behavior is invoked.
  9. A derived class can break the polymorphism of a derived method but must signal that intent with the keywordnew. This is unusual, complex and can be confusing, but is provided to allow for versioning of derived classes. Typically, you will use the keyword overrides (rather than new) to indicate that you are modifying the behavior of the base class’s method.
  10. A method marked asabstracthas no implementation—instead, it provides a virtual method name and signature that all derived classes must override. Any class with an abstract method is an abstract class, and cannot be instantiated.
  11. Any class marked assealed cannot be derived from.
  12. In C#, all classes (and built-in types) are ultimately derived from theObject class, implicitly, and thus inherit a number of useful methods such asToString.
  13. When you pass a value type to a method or collection that expects a reference type, the value type is “boxed” and must be explicitly “unboxed” when retrieved.
  14. Generics make boxing and unboxing less common, and well-designed code will have little or no boxing or unboxing.

Quiz

Question 11-1. What is the relationship between specialization and generalization?

Question 11-2. How is specialization implemented in C#?

Question 11-3. What is the syntax for inheritance in C#?

Question 11-4. How do you implement polymorphism?

Question 11-5. What are the two meanings of the keywordnew?

Question 11-6. How do you call a base class constructor from a derived class?

Question 11-7. What is the difference between public, protected, and private?

Question 11-8. What is an abstract method?

Question 11-9. What is a sealed class?

Question 11-10. What is the base class of Int32?

Question 11-11. What is the base class of any class you create if you do not otherwise indicate a base class?

Question 11-12. What is boxing?

Question 11-13. What is unboxing?

Exercises

Exercise 11-1. Create a base class, Telephone, and derive a class ElectronicPhonefrom it. InTelephone, create a protected string memberphonetype, and a public methodRing()that outputs a text message like this: “Ringing the .” InElectronicPhone, the constructor should set thephonetypeto “Digital.” In theRun()method, callRing() on theElectronicPhoneto test the inheritance.

Exercise 11-2. Extend Exercise 11-1 to illustrate a polymorphic method. Have the derived class override theRing()method to display a different message.

Exercise 11-3. Change theTelephoneclass to abstract, and makeRing()an abstract method. Derive two new classes fromTelephone:DigitalPhoneandTalkingPhone. Each derived class should set thephonetype, and override theRing()method.