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. Taking some code from our polymorphism example, as follows: class Program 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. 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. If you represent your class hierarchy this way, with the base class at the top and the leaves somewhere below, then up-casting and down-casting become literal - something that moves up the page from a leaf toward the base is an up-cast and something that moves down the page from the base toward a leaf is a down-cast. Up casting If you convert a higher datatype to lower datatype, it is known as narrowing (assigning higher data type value to the lower data type variable). ![]() Polymorphism is a powerful aspect of object oriented programming. How do you upcast and downcast the same object in Java Java 8 Object Oriented Programming Programming Converting one data type to others in Java is known as casting. 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. |