Wayne Scicluna
Wayne Scicluna

Reputation: 47

inherited variable of class2 is different from class1 (C#)

I just made a class Shapes and an other 2 classes ('Triangle' & 'Square') which inherit from 'Shapes'.

public class Shapes
{
    private int sides;
}

public class Triangle : Shapes
{
    public void init()
    {
        int sides = 3;
        throw new System.NotImplementedException();
    }
}

public class Square : Shapes
{
    public void init()
    {
        int sides = 4;
        throw new System.NotImplementedException();
    }
}

Code is designed using Classdiagram

Question: How should I call the class so that it shows how many sides does a shape has?

Thanks

Upvotes: 0

Views: 77

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You need a protected member sides which is used within the init-section of every shape:

public class Shapes
{
    protected readonly int sides;
    public int NumberOfSides { get { return sides; } } 
}

public class Triangle : Shapes
{
    public Triangle()
    {
        this.sides = 3;
    }
}

public class Square : Shapes
{
    public Square()
    {
        this.sides = 4;
    }
}

As Farhad Jabiyev mentioned using constructors is the usual way to initialize a new instance (see my code above)

Now when you call Shape#NumberOfSides you get 3 for Triangle and 4 for Square:

Shape square = new Square();
int number = square.NumberOfSides();

Upvotes: 2

David Pilkington
David Pilkington

Reputation: 13620

You need to add a property on the class that has an accessor like this

public class Shapes
{
    private int sides;

    public int NumberOfSides { get { return sides; } } 
}

Then you can go mySquare.NumberOfSides

Upvotes: 0

Related Questions