In the last example, let's take a look at the abstraction and Polymorphism of C. First, let's define these two new terms. Abstract: Extracts public parts from multiple objects and merges them into a separate Abstract class. In this example, we will create an abstract class Shape ). Every Shape has a way to return its color. Whether it is a square, a circle, or a rectangle, the return color method is always the same. Therefore, this method can be extracted and put into the parent Shape. In this way, if we have 10 different shapes and need to have the return color method, now we only need to create a method in the parent class. We can see that the use of abstraction makes the code shorter.
In the field of object-oriented programming, Polymorphism is the ability of objects or methods to make different behaviors based on different classes. In the following example, the abstract class Shape has a getArea () method, which has different functions for different shapes (Circular, square, or rectangular.
The following code is used:
Public abstract class Shape {
Protected string color;
Public Shape (string color ){
This. color = color;
}
Public string getColor (){
Return color;
}
Public abstract double getArea ();
}
Public class Circle: Shape {
Private double radius;
Public Circle (string color, double radius): base (color ){
This. radius = radius;
}
Public override double getArea (){
Return System. Math. PI * radius;
}
}
Public class Square: Shape {
Private double sideLen;
Public Square (string color, double sideLen): base (color ){
This. sideLen = sideLen;
}
Public override double getArea (){
Return sideLen * sideLen;
}
}
/*
Public class Rectangle: Shape
...
*/
Public class Example3
{
Static void Main ()
{
Shape myCircle = new Circle ("orange", 3 );
Shape myRectangle = new Rectangle ("red", 8, 4 );
Shape mySquare = new Square ("green", 4 );
System. Console. WriteLine ("the circle color is" + myCircle. getColor ()
+ "The area is" + myCircle. getArea () + ".");
System. Console. WriteLine ("the rectangle color is" + myRectangle. getColor ()
+ "Its area is" + myRectangle. getArea () + ".");
System. Console. WriteLine ("the color of the square is" + mySquare. getColor ()
+ "Its area is" + mySquare. getArea () + ".");
}
}