Valerie Meunier

Valerie Meunier

  • 824
  • 693
  • 72.2k

code works but not optimal

Jun 12 2022 3:31 PM

Hi

This code calculates the area of a square and a rectangle.It works but i'm not satisfied about the code and i have some questions.
1) With those constructors in the class Polygoon and in class Square and Rectangle, i'm compelled to put the length and width twice in the Main method: one time in the constructor call and one time in call of the Opp method. Something is wrong here, i think.

2) The area of the square requires only one parameter (length), but i'm compelled to use the two same paramaters in the override methods of both square and rectangle as the abstract method. How to avoid that? 
Thanks for help.

V

using System;
public abstract class Polygoon
{
    private int lengte;
    private int width;

    public int Lengte
    {
        get { return lengte; }
    }

    public int Width
    {
        get { return width; }
    }

    // Constructor
    public Polygoon(int l, int b)
    {
        lengte = l;
        width = b;
    }

    // Constructor
    public Polygoon(int l)
    {
        lengte = l;
    }

    public abstract int Area(int lengte, int width);
}

public class Square : Polygoon
{
    public Square(int l) : base(l)
    { }

    public override int Area(int lengte, int width)
    {
        int Area = lengte * lengte;
        return Area;
    }
}

public class Rectangle : Polygoon
{
    public Rectangle(int l, int b) : base(l, b)
    { }

    public override int Area(int lengte, int width)
    {
        int Area = lengte *width;
        return Area;
    }
}

public class Program
{
    static void Main(string[] args)
    {
        Square sq = new Square(3);
        Rectangle rect = new Rectangle(3,4);
        int s = sq.Area(3,3);
        int r = rect.Area(3, 4);
        Console.WriteLine("Areaervlakte van de vierkant is {0} en van de rechthoek {1}.", s, r);
    }
}
 


Answers (1)