![]() ![]() We will modify the code above, to ensure the correct method is called to fill our shapes as they are drawn. ![]() Within the foreach statement, we have to test the type of shape being drawn before we down-cast, we will use the is keyword to test type. How do we know what type we have to down-cast to in order to call the correct routine to fill the shape? We have Circle and Square in our array of type Shape. However, in objects, there are only two types of objects, i.e. Just like the data types, the objects can also be typecasted. In this article, the concept of typecasting for objects is discussed. Taking some code from our polymorphism example, as follows: class Program Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. public class ShapeĬonsole.WriteLine("Drawing a SHAPE at ", m_xpos, m_ypos) Our shape class will implement a constructor that will accept an X and Y co-ordinate and a method that will draw our shape. So how do we implement this concept in C#?įirst we need to design our base class, this will be called Shape. So, what we are saying is a shape can take on many forms or has multiple forms. Upcasting and downcasting in Java Casting : Taking an object of one type and assigning it to reference variable of another type. A square, rectangle and a triangle are also shapes. Ask yourself, what is a circle? Most would say a circle is a shape. According to many searches on the Internet to find a definitive meaning, I have found two that seem to explain it quite nicely, these are "Having many forms" and "Having multiple forms".Ĭonsider the following. Polymorphism is a powerful aspect of object oriented programming. This has expanded the article further and when you have finished reading it, you should hopefully understand the three concepts better. ![]() Having thought further about it, one way I found was to introduce the concept of polymorphism to help explain up and down-casting. Having started writing the article, I was struggling to find an ideal way to describe these two concepts. The original aim of this article was to explain Up-casting and Down-casting. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |