Im was reading an example of simple inheritence and came across the basic idea that a square is a base type and a rectangle is derived from a square.
The example for setting the square dimensions used a property called Size
.
The example for the rectangle then went on to use Width
and Height
.
This didnt make sense in my head, so I coded it.
The problem seems to be that when accessing rectangle
, there will always be a confusing property called 'Size
' present.
Have I got this right? Or is there a way to hide other classes from seeing Size
when looking at rectangle
?
public class square
{
public int Size { get; set; }
public square(int size)
{
this.Size = size;
}
}
public class rectangle : square
{
public int Width { get { return base.Size; } set { base.Size = value; } }
public int Height { get; set; }
public rectangle(int width, int height)
: base(width)
{
Height = height;
}
}
Inheritance is one of four pillars of Object-Oriented Programming (OOPs). It is a feature that enables a class to acquire properties and characteristics of another class. Inheritance allows you to reuse your code since the derived class or the child class can reuse the members of the base class by inheriting them.
Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs.
C# compiler is designed not to support multiple inheritence because it causes ambiguity of methods from different base class. This is Cause by diamond Shape problems of two classes If two classes B and C inherit from A, and class D inherits from both B and C.
This is because C# does not support multiple inheritance with classes. Although with interfaces, multiple inheritance is supported by C#. Inheriting Constructors: A subclass inherits all the members (fields, methods) from its superclass.
You are 100% right that this is backwards inheritance. Instead, you should have a Square
class inherit from a Rectangle
class, since a square is a special kind of rectangle.
Then, you get something like
public class Rectangle
{
public int Width { get; private set; }
public int Height { get; private set; }
public Rectangle(int width, int height)
{
if (width <= 0 || height <= 0)
throw new ArgumentOutOfRangeException();
Width = width;
Height = height;
}
}
public class Square : Rectangle
{
public int Size
{
get
{
return Width;
}
}
public Square(int size)
: base(size, size)
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With