Polymorphism with an example?

Answer Posted / bilal dooply

Polymorphism is a property in which a single object can have more than 1 form.

Example [Code in VB.NET]:

Class Animals
'Walk() is declared Overridable

Overridable Public Sub Walk()
Console.Writeline ("Walking")
End Sub
End Class

Class Dog
Inherits Animals
'Let us make Dog is walking

'Walk() is overriding Walk() in its base class (Animals)

Overrides Public Sub Walk()
Console.Writeline ("Walking")
'Important: As you expect, any call to Walk() inside this class
'will invoke the Walk() in this class. If you need to
'call Walk() in base class, you can use MyBase keyword.
'Like this

'Mybase.Speak()

End Sub
End Class

Class MainClass
'Our main function

Shared Sub Main()
'Let us define Tommy as a Animal (base class)

Dim Tommy as Animals
'Now, I am assiging an Indian (derived class)

Tommy = new Dogs
'The above assignment is legal, because

'Dogs IS_A Animals.

'Now, let me call Walk as

Tommy.Walk()
'Which Walk() will work? The Walk() in Dogs, or the

'Walk() in Animals?

'The question arises because, Tommy is declared as a Animals,

'but an object of type Dogs is assigned to Tommy.

'The Answer is, the Walk() in Dogs will work. This is because,

'most object oriented languages like Vb.net can automatically

'detect the type of the object assigned to a base class variable.

'This is called Polymorphism

End Sub
End Class

Is This Answer Correct ?    7 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is polymorphism explain?

994


What is multilevel inheritance explain with example?

878


What is the real life example of polymorphism?

867


i am getting an of the type can not convert int to int *. to overcome this problem what we should do?

2077


There are two base class B1,B2 and there is one class D which is derived from both classes, Explain the flow of calling constructors and destructors when an object of derived class is instantiated.

1722


Why do we use encapsulation in oops?

767


write a code for this. serial_number contained in the header of the file will be read , if this serial number is less than a previous serial number within a successfully processed file, or is the same as another serial number within a successfully processed file, or if the field contains anything other than 7 digits, then the file must error with the reason ‘Invalid SERIAL_NUMBER’.

2005


What language is oop?

788


hi all..i want to know oops concepts clearly can any1 explain??

1905


what type of question are asked in thoughtworks pair programming round ?

1980


Can enum be null?

784


What is the difference between static polymorphism and dynamic polymorphism?

866


State what is encapsulation and friend function?

963


Why do we use class?

833


What is inheritance in simple words?

831