Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
New Feature: Community Sites:
Create your own .NET community website and start earning from Google AdSense !
It's Free !
|
polymorphism
Posted Date:
28 Aug 2008
Total Responses:
9
|
Posted By: narendra Member Level: Silver Points: 1
|
hi friend plz help me
what is meant by run time polymorphism
|
Responses
|
| Author: Bindu Bujji 28 Aug 2008 | Member Level: Gold | Rating: Points: 6 | In runtime polymorphism ... the code is called at run time according to need or given conditions.
suppose there r two methods namely Add() one in super class and other is in sub class.both have the same name and same parameters.
so we have to choose that which method from them shld called at run time i.e. of super class or of sub class.by polymorphism we do that.
ex:-
class A
{
int add(){//code of the method}
//some other code
}
class B extends A
{
int add(){//code of the method}
//some other code
}
class AB
{
public static void main(String s[])
{
A ob1;
ob1=new A();
int i=ob1.add();//will call the method of super class.
ob1=new B();// sub class's reference can be assigned to super class address but not vice versa.to do that we have to type cast the reference of the sub class in reference of the super class.
int j=ob1.add();//will call the method of sub class
}
}
Hope this Helps Bindu
| | Author: D.Jeya kumar(JK) 29 Aug 2008 | Member Level: Diamond | Rating: Points: 3 | HI
check the below link it is expliend with example and defination
http://discuss.joelonsoftware.com/default.asp?dotnet.12.460011.9
Regards JK
| | Author: Athira Appukuttan 29 Aug 2008 | Member Level: Diamond | Rating: Points: 6 | In runtime polymorphism ... the code is called at run time according to need or given conditions.
suppose there r two methods namely Add() one in super class and other is in sub class.both have the same name and same parameters.
so we have to choose that which method from them shld called at run time i.e. of super class or of sub class.by polymorphism we do that.
ex:-
class A
{
int add(){//code of the method}
//some other code
}
class B extends A
{
int add(){//code of the method}
//some other code
}
class AB
{
public static void main(String s[])
{
A ob1;
ob1=new A();
int i=ob1.add();//will call the method of super class.
ob1=new B();// sub class's reference can be assigned to super class address but not vice versa.to do that we have to type cast the reference of the sub class in reference of the super class.
int j=ob1.add();//will call the method of sub class
}
}
| | Author: Legend 29 Aug 2008 | Member Level: Silver | Rating: Points: 6 | Same function implements different tasks by virtual and override. Virtual – To hide existing class method Override – Enable OR implement current class method
ex:-
class A
{
int add(){//code of the method}
//some other code
}
class B extends A
{
int add(){//code of the method}
//some other code
}
class AB
{
public static void main(String s[])
{
A ob1;
ob1=new A();
int i=ob1.add();//will call the method of super class.
ob1=new B();// sub class's reference can be assigned to super class address but not vice versa.to do that we have to type cast the reference of the sub class in reference of the super class.
int j=ob1.add();//will call the method of sub class
}
}
| | Author: Legend 29 Aug 2008 | Member Level: Silver | Rating: Points: 6 | Here is Another (It will explains clearly)
What is polymorphism?
The meaning of the word polymorphism is something like one name, many forms.
How does C# implement polymorphism?
Polymorphism manifests itself in C# in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods, which were discussed in a previous lesson).
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
Three distinct forms of polymorphism
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in C#:
Method overloading Method overriding through inheritance Method overriding through the C# interface I covered method overloading as one form of polymorphism (compile-time polymorphism) in a previous lesson. I also explained automatic type conversion and the use of the cast operator for type conversion in a previous lesson.
The essence of runtime polymorphic behavior
Methods are invoked on references to objects. Typically, those references are stored in reference variables, or in the elements of a collection such as an array or a hashtable. With runtime polymorphism based on method overriding, the decision as to which version of a method will be executed is based on the actual type of the object whose reference is stored in the reference variable or element, and not on the type of the reference variable or element on which the method is invoked.
Late binding
The decision as to which version of the method to invoke cannot be made at compile time. That decision must be deferred and made at runtime. This is sometimes referred to as late binding, although everyone may not agree with this interpretation of that term.
| | Author: Legend 29 Aug 2008 | Member Level: Silver | Rating: Points: 6 | Sample Code and Discussion
Operational description of runtime polymorphism
Here is an operational description of runtime polymorphism as implemented in C# through inheritance and method overriding:
Assume that a class named SuperClass defines a method named method. Assume that a class named SubClass extends SuperClass and overrides the method named method. Assume that a reference to an object of the class named SubClass is assigned to a reference variable named ref of type SuperClass. Assume that the method named method is then invoked on the reference variable using the following syntax: ref.method() Result: The version of the method named method that will actually be executed is the overridden version in the class named SubClass, and is not the version that is defined in the class named SuperClass. This is runtime polymorphism.
Runtime polymorphism is very powerful
As you gain more experience with C#, you will learn that much of the power of OOP using C# is centered on runtime polymorphism using class inheritance, interfaces, and method overriding. (The use of interfaces for polymorphism will be discussed in a subsequent lesson.)
An important attribute of runtime polymorphism
The decision as to which version of the method to execute is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is invoked.
Why is it called runtime polymorphism?
The reason that this type of polymorphism is often referred to as runtime polymorphism is because the decision as to which version of the method to execute cannot be made until runtime. The decision cannot be made at compile time (as is the case with overloaded methods).
Why defer the decision?
The decision cannot be made at compile time because the compiler has no way of knowing (when the program is compiled) the actual type of the object whose reference will be stored in the reference variable.
In an extreme case, for example, the object might be obtained at runtime from a network connection of which the compiler has no knowledge.
Could be either type
For the situation described above, that object could just as easily be of type SuperClass as of type SubClass. In either case, it would be valid to assign the object's reference to the same superclass reference variable.
If the object were of the SuperClass type, then an invocation of the method named method on the reference would cause the version of the method defined in SuperClass, and not the version defined in SubClass, to be executed. (The version executed is determined by the type of the object and not by the type of the reference variable containing the reference to the object.)
Sample Program
Let's take a look at a sample program that illustrates runtime polymorphism using class inheritance and overridden methods. The name of the program is Poly03. A complete listing of the program is shown in Listing 7 near the end of the lesson.
The class named A
I will discuss this program in fragments. Listing 1 shows the definition of a class named A, which extends the class named Object by default.
(Remember that any class that doesn't extend some other class automatically extends Object by default, and it is not necessary to show that explicitly.)
/*File Poly03.cs Copyright 2002, R.G.Baldwin **************************************/ using System;
class A{ public virtual void m(){ System.Console.WriteLine( "m in class A"); }//end method m() }//end class A
Listing 1
The class named A defines a simple method named m().
A virtual method
Note that the method named m is declared to be virtual. This means that it is allowable to override this method in a subclass.
(If you come from a Java background, you will note that this is the reverse of the situation in Java. In Java, all methods are virtual by default unless they are declared to be final.)
Behavior of the method
The behavior of the method, as defined in the class named A, is to display a message indicating that it has been invoked, and that it is defined in the class named A.
This message will allow us to determine which version of the method is executed in each case discussed later.
The class named B
Listing 2 shows the definition of a class named B that extends the class named A. class B : A{ public override void m(){ System.Console.WriteLine( "m in class B"); }//end method m() }//end class B
Listing 2
The class named B overrides (redefines) the method named m(), which it inherits from the class named A.
The override declaration
Note the use of the override declaration in Listing 2. In C#, if one method overrides another, it is necessary to declare that fact.
(Once again, if you come from a Java background, you will note that this is just the reverse of the situation in Java. In Java, a method whose name, return type, and formal argument list matches an inherited method will automatically override the inherited method.)
A compiler warning
If you fail to make the override declaration in Listing 2, you will get a compiler warning that reads something like the following:
warning CS0114: 'B.m()' hides inherited member 'A.m()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
I'm not going to get into a discussion of the difference between overriding and hiding in this lesson. Perhaps I will find the time to provide such a discussion in a future lesson.
Behavior of the overridden method
Like the inherited version, the overridden version displays a message indicating that it has been invoked. However, the message is different from the message displayed by the inherited version discussed above. The overridden version tells us that it is defined in the class named B.
(According to the current jargon, the behavior of the overridden version of the method is appropriate for an object instantiated from the class named B.)
Again, this message will allow us to determine which version of the method is executed in each case discussed later.
The driver class
Listing 3 shows the beginning of the driver class named Poly03. public class Poly03{ public static void Main(){ Object var = new B(); //Following will compile and run ((B)var).m();
Listing 3
A new object of the class B
Note that the code in the Main method begins by instantiating a new object of the class named B, and assigning the object's reference to a reference variable of type Object.
(This is legal because an object's reference can be assigned to any reference variable whose type is a superclass of the class from which the object was instantiated. The class named Object is the superclass of all classes.)
Downcast and invoke the method
If you read the previous lesson, it will come as no surprise to you that the second statement in the Main method, which casts the reference down to type B and invokes the method named m() on it, will compile and execute successfully.
Which version was executed?
The execution of the method produces the following output on the computer screen:
m in class B
By examining the output, you can confirm that the version of the method that was overridden in the class named B is the version that was executed.
Why was this version executed?
This should also come as no surprise to you. The cast converts the type of the reference from type Object to type B.
You can always invoke a public method belonging to an object using a reference to the object whose type is the same as the class from which the object was instantiated.
Not runtime polymorphic behavior
Just for the record, the above invocation of the method does not constitute runtime polymorphism (in my opinion). I included that invocation of the method to serve as a backdrop for what follows.
(If this is runtime polymorphism, it is not a very significant example, because there was no requirement for the runtime system to decide between different methods having the same name. The runtime system simply executed a method belonging to an object using a reference of the same type as the object.)
This is runtime polymorphic behavior
However, the invocation of the method in Listing 4 does constitute runtime polymorphism. //Following will also compile // and run due to polymorphic // behavior. ((A)var).m();
Listing 4
The statement in Listing 4 casts the reference down to type A and invokes the method named m() on that reference. It may, or may not come as a surprise to you that the invocation of the method shown in Listing 4 also compiles and runs successfully.
The method output
Here is the punch line. Not only does the statement in Listing 4 compile and run successfully, it produces the following output, (which is exactly the same output as before):
m in class B
Same method executed in both cases
It is extremely important to note that this output, (produced by casting the reference variable to type A instead of type B), is exactly the same as that produced by the earlier invocation of the method when the reference was cast to type B. This means that the same version of the method was executed in both cases.
This confirms that even though the type of the reference was converted to type A, (rather than type Object or type B), the overridden version of the method defined in class B was actually executed.
This is runtime polymorphic behavior in a nutshell.
The version of the method that was executed was based on the actual type of the object, B, and not on the type of the reference, A. This is an extremely powerful and useful concept.
Another invocation of the method
Now take a look at the statement in Listing 5. Will this statement compile and execute successfully? (Obviously, the answer to the question is given in Listing 5). If so, which version of the method will be executed? //Following will not compile //var.m();
Listing 5
Compiler error
The code in Listing 5 attempts, unsuccessfully, to invoke the method named m() using the reference variable named var, which is of type Object. The result is a compiler error, which reads something like the following:
error CS0117: 'object' does not contain a definition for 'm'
Some important rules
The Object class does not define a method named m(). Therefore, the overridden method named m() in the class named B is not an overridden version of a method that is defined in the class named Object.
Necessary, but not sufficient
Runtime polymorphism based on class inheritance requires that the type of the reference variable be a superclass of the class from which the object (on which the method will be invoked) is instantiated. (At least this requirement is true if a significant decision among methods is to be made.)
However, while necessary, that is not sufficient to ensure runtime polymorphic behavior.
The type of the reference variable must also be the name of a class that either defines or inherits the method that will ultimately be invoked on the object.
This method is not defined in the Object class
Since the class named Object does not define (or inherit) the method named m(), a reference of type Object does not qualify as a participant in runtime polymorphic behavior in this case. The attempt to use it as a participant results in the compiler error given above.
One additional scenario
Before leaving this topic, let's look at one additional scenario to help you distinguish what is, and what is not, runtime polymorphism. Consider the code shown in Listing 6. //Instantiate obj of class A var = new A(); //Invoke the method on it ((A)var).m();
Listing 6
A new object of type A
The code in Listing 6 instantiates a new object of the class named A, and stores the object's reference in the original reference variable named var of type Object.
(As a side note, this overwrites the previous contents of the reference variable with a new reference and causes the object whose reference was previously stored there to become eligible for garbage collection.)
Downcast and invoke the method
Then the code in Listing 6 casts the reference down to type A, (the type of the object to which the reference refers), and invokes the method named m() on the downcast reference.
The output
As you would probably predict, this produces the following output on the computer screen:
m in class A
In this case, the version of the method defined in the class named A, (not the version defined in B) was executed.
Not polymorphic behavior
Again, in my view, this is not runtime polymorphic behavior (at least it isn't a very useful form of polymorphic behavior). This code simply converts the type of the reference from type Object to the type of the class from which the object was instantiated, and invokes one of its methods. Nothing special takes place regarding a selection among different versions of the method.
Some authors may disagree
While some authors might argue that this is technically runtime polymorphic behavior, in my view at least, it does not illustrate the real benefits of runtime polymorphic behavior. The benefits of runtime polymorphic behavior generally accrue when the actual type of the object is a subclass of the type of the reference variable containing the reference to the object.
Once again, what is runtime polymorphism?
As I have discussed in this lesson, runtime polymorphic behavior based on inheritance occurs when
The type of the reference is a superclass of the class from which the object was instantiated The version of the method that is executed is the version that is either defined in, or inherited into, the class from which the object was instantiated More than you ever wanted to hear
And that is probably more than you ever wanted to hear about runtime polymorphism based on inheritance.
A future lesson will discuss runtime polymorphism based on the C# interface. From a practical viewpoint, you will find the rules to be similar but somewhat different in the case of the C# interface.
| | Author: chandramohan 29 Aug 2008 | Member Level: Gold | Rating: Points: 6 | polymorphism -an entity existing in different forms at the same time. Polymorphism is of two types. Static polymorphism and dynamic polymorphism. Run time polymorphism refers to dynamic polymorphism wherein an entity changes it's form depending on the cirumstances
Ex: Class A { Public void test(){ System.out.println(“This is Base Class”); } } Class B extends A{ Public void test(){ System.out.println(“This is Child Class”); }
} Class RuntimePoly{ Public static void main(){ A a = new A(); B b = new B(); A baseClassVar; baseClassVar = a; baseClassVar.test();
baseClassVar = b; baseClassVar.test();
} }
| | Author: Legend 29 Aug 2008 | Member Level: Silver | Rating: Points: 6 | A complete listing of the program(Clear Example)
/*File Poly03.cs Copyright 2002, R.G.Baldwin
This program illustrates downcasting and polymorphic behavior
Program output is: m in class B m in class B m in class A **************************************/ using System;
class A{ public virtual void m(){ System.Console.WriteLine( "m in class A"); }//end method m() }//end class A //===================================//
class B : A{ public override void m(){ System.Console.WriteLine( "m in class B"); }//end method m() }//end class B //===================================//
public class Poly03{ public static void Main(){ Object var = new B(); //Following will compile and run ((B)var).m(); //Following will also compile // and run due to polymorphic // behavior. ((A)var).m(); //Following will not compile //var.m(); //Instantiate obj of class A var = new A(); //Invoke the method on it ((A)var).m(); }//end Main }//end class Poly03 //===================================//
Please comment me , How is my Responses? Is my responses helpful or NOT?
| | Author: Ravi Kiran Nedunuri 27 Sep 2008 | Member Level: Gold | Rating: Points: 6 | HI In simple terms, polymorphism lets you treat derived class members just like their parent class' members.
Polymorphism is the process of using an operator or function in different ways for different set of inputs given.
More precisely, polymorphism (object-oriented programming theory) is the ability of objects belonging to different types to respond to method calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, so this behavior can be implemented at run time (this is called late binding or dynamic binding).
The different objects involved only need to present a compatible interface to the clients (the calling routines). That is, there must be public methods with the same name and the same parameter sets in all the objects. In principle, the object types may be unrelated, but since they share a common interface, they are often implemented as subclasses of the same parent class. Though it is not required, it is understood that the different methods will also produce similar results (for example, returning values of the same type).
Advantages of polymorphism Polymorphism allows client programs to be written based only on the abstract interfaces of the objects which will be manipulated (interface inheritance). This means that future extension in the form of new types of objects is easy, if the new objects conform to the original interface. In particular, with object-oriented polymorphism, the original client program does not even need to be recompiled (only relinked) in order to make use of new types exhibiting new (but interface-conformant) behavior.
In C++, for instance, this is possible because the interface definition for a class defines a memory layout, the virtual function table describing where pointers to functions can be found. Future, new classes can work with old, precompiled code because the new classes must conform to the abstract class interface, meaning that the layout of the new class's virtual function table is the same as before; the old, precompiled code can still look at the same memory offsets relative to the start of the object's memory in order to find a pointer to the new function. It is only that the new virtual function table points to a new implementation of the functions in the table, thus allowing new, interface-compliant behavior with old, precompiled code.
Since program evolution very often appears in the form of adding types of objects (i.e. classes), this ability to cope with and localize change that polymorphism allows is the key new contribution of object technology to software design polymorphism means same operation may behave differently on different classes
method overriding is runtime polymorphism method overloading is compile time polymorphism
method overloading:method with same name but with different arguments
ex:class a { void hello() { } void hello (string s) { } } method overriding: method overriding occurs when child class declares a method that has the same type of arguments as a method declared by one of its super class.
Regards N.RaviKiran
|
| Post Reply |
|
|
|
You must Sign In to post a response.
|
|
|
|