Question: C# programing Dynamic Polymorphism-Part 1 Given two integer numbers N1 and N2. Find area of Triangle and Rectangle by creating Shape type pointing to Triangle
C# programing
Dynamic Polymorphism-Part 1
Given two integer numbers N1 and N2. Find area of Triangle and Rectangle by creating Shape type pointing to Triangle and Rectangle instances.
Write 2 functions inside 'ProblemSolution' class.
Function 1:
solution4Triangle that accepts two integer parameters and return type should be Shape. This method should create instance of Triangle and call calculateArea method to calculate area and return the created instance.
Function 2:
solution4Rectangle that accepts two integer parameters and return type should be Shape. This method should create instance of Rectangle and call calculateArea method to calculate area and return the created instance.
Note: 'Shape', 'Triangle' and 'Rectangle' classes already created.
Input 2 3
Output Area of Triangle = 3.0 Area of Rectangle = 6 .0
Our two cents: Try changing the return type to Triangle/Rectangle to notice change in behavior.
Please fill in the partial code below:
using System; using System.Collections.Generic; using System.Linq; public class ProblemSolution { public Shape solution4Triangle (int N1, int N2) {
//write your code here
}
public Shape solution4Rectangle (int N1, int N2) {
//write your code here
} } public class Triangle : Shape { int base1, height; public Triangle (int base1, int height) { this.base1 = base1; this.height = height; } public override void calculateArea () { this.area = (base1 * height) / 2; } }
public class Rectangle : Shape { int length, width; public Rectangle (int length, int width) { this.length = length; this.width = width; } public override void calculateArea () { this.area = length * width; } }
public class Shape { public float area; public virtual void calculateArea () { Console.WriteLine ("Dummy method"); } }
class DriverMain {
public static void Main () { int N1 = int.Parse (Console.ReadLine ()); int N2 = int.Parse (Console.ReadLine ()); ProblemSolution problemSolution = new ProblemSolution (); Shape shape = new Shape (); shape = problemSolution.solution4Triangle (N1, N2); Console.WriteLine ("Area of Triangle = " + shape.area.ToString("0.0")); shape = problemSolution.solution4Rectangle (N1, N2); Console.WriteLine ("Area of Rectangle = " + shape.area.ToString("0.0")); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
