Filip Nilsson
Filip Nilsson

Reputation: 407

Overriding properties doesn't work

My class Ellipse should inherit from my class Shape but I get this error message:

Error 1 'ConsoleApplication3.Ellipse' does not implement inherited abstract member 'ConsoleApplication3.Shape.Perimeter.get'

I also get the error message that I'm hiding Area, a property in Ellipse.

Can anyone help me please?

My shape class looks like this:

public abstract class Shape
{
    //Protected constructor
    protected Shape(double length, double width)
    {
        _length = length;
        _width = width;
    }


    private double _length;
    private double _width;

    public abstract double Area
    {
        get;
    }

And my ellipse class is:

class Ellipse : Shape
{
    //Constructor
    public Ellipse(double length, double width)
        :base(length, width)
    {

    }

    //Egenskaper
    public override double Area
    {
        get
        {
            return Math.PI * Length * Width;
        }
    }
}

Upvotes: 1

Views: 189

Answers (2)

Surjit Samra
Surjit Samra

Reputation: 4662

May be this is what you after as you have not declared Length , Width any where in your Ellipse class so you might be getting compilation errors, to compile this you need enhance visibility of _length and _width properties of your base class Shape.

public abstract class Shape
{
  //Protected konstruktor
  protected Shape(double length, double width)
  {
    _length = length;
    _width = width;
  }

  // have these variables protected since you instantiate you child through the parent class.       

  protected double _length;
  protected double _width;

  public abstract double Area
  {
    get;
  }
}
class Ellipse : Shape
{
  //Konstruktor
  public Ellipse(double length, double width)
    : base(length, width)
  {

  }

  //Egenskaper
  public override double Area
  {
    get
    {
      // use the variable inherited since you only call the base class constructor.
      return Math.PI * _length * _width;
    }
  }
}

Upvotes: 1

Patrick McDonald
Patrick McDonald

Reputation: 65461

You need to use the override modifier on the Area and Perimeter properties in your Ellipse class, e.g.

public override double Area { get; }

public override double Perimeter { get; }

A tip for you in Visual Studio, put the cursor inside the text 'Shape' (in your ellipse class) and press Ctrl + .. This should add stubs for members you haven't implemented

Upvotes: 5

Related Questions