Reputation: 5730
I am sorry for my question is a little theoretical
I am new to OOP and studying the following code.
public interface IShape
{
double getArea();
}
public class Rectangle : IShape
{
int lenght;
int width;
public double getArea()
{
return lenght * width;
}
}
public class Circle : IShape
{
int radius;
public double getArea()
{
return (radius * radius) * (22 / 7);
}
}
public class SwimmingPool
{
IShape innerShape;
IShape outerShape;
SwimmingPool(IShape _innerShape, IShape _outerShape)
{
//assignment statements and validation that poolShape can fit in borderShape;
}
public double GetRequiredArea()
{
return outerShape.getArea() - innerShape.getArea();
}
}
This code calculate area of different shapes. I can see constructor of SwimingPool class but I am not getting how to pass values to constructor. I have not done programming using Interfaces before. Please guide me 3 things:
Thanks for your time and help.
Upvotes: 1
Views: 17674
Reputation: 6554
Well, you are using interfaces so in your SwimmingPool
class, the constructor will require two IShape
parameters. Since you need an implementation in order to use your interface, such as your Rectangle
and Circle
, you would simply do something like this:
class Pool
{
private IShape _InnerShape;
private IShape _OuterShape;
public Pool(IShape inner, IShape outer)
{
_InnerShape = inner;
_OuterShape = outer;
}
public double GetRequiredArea()
{
return _InnerShape.GetArea() - _OuterShape.GetArea();
}
}
and the usage would be something like
IShape shape1 = new Rectangle() { Height = 1, Width = 3 };
IShape shape2 = new Circle() { Radius = 2 };
Pool swimmingPool = new Pool(shape1, shape2);
Console.WriteLine(swimmingPool.GetRequiredArea());
It seems, based on your comment, is that you want to test if an object implements an interface.
You can do something like this
if (shape1 is Circle) //...
Upvotes: 4
Reputation: 13755
Just do something like this
SwimmingPool(IShape innerShape, IShape outerShape)
{
this.innerShape = innerShape;
this.outerShape = outerShape;
this.Validate();
}
private void Validate()
{
// or some other condition
if ( GetRequiredArea() < 0 ){
throw new Exception("The outer shape must be greater than the inner one");
}
}
Upvotes: 4