Newbie Question which my course instructor has effectively confused the tar out of me. Is-A relationship is when say a Dog is a animal. Then you'd make Animal be the Base class with Dog as a derivative class.
But for our Class Project I have to make a class based on an interface. With a separate class which only has one method to give a random number. Seemingly they aren't really related, but I have to call the randomNumber Method from the main class.
His question during the instructions (which are terrible) say to figure out if this is an IS-A or HAS-A relationship. Based on the facts I'd say this is a HAS-A relationship, but I have no idea how to reference the class, but to make a variable assigned to the class so I can use it.
Is there another way to Reference the class which I don't know?
Devices randomMeasure = new Devices(); //Random measurement Class
this.mostRecentMeasure = randomMeasure.GetMeasurement();
If your class inherits from the other class, it is an "IS-A" relationship.
If the class is passed to the other class in the constructor this is a "HAS-A" relationship.
e.g.
public class foo : bar
{
// IS-A
}
public interface IBar
{
}
public class Bar : IBar
{
}
public class Foo : IBar
{
private Bar _bar;
public foo(Bar bar)
{
_bar = bar;
}
// HAS-A
}
However, it's not obvious what it is your've asking. In the second case, Foo
IS-A IBar
and HAS-A Bar
.
An Interface is a Can-Do relationship.
You can assign an instance of a class to any variable that is of the type of
In your example (case 3), this means:
IDevice randomMeasure = new Devices();
randomMeasure.GetMeasurement();
This concept is referred to as polymorphism.
This is a IS-A relationship, the
To reference it, you should create an instance of the concrete class and assign it to the variable of the interface type:
interface IMeasureable
{
public int GetMeasurement();
}
class Device : IMeasureable
{
public int GetMeasurement()
{
return ....
}
}
class App
{
public void Main()
{
IMeasureable thing = new Device();
int x = thing.GetMeasurement();
}
}
To answer your question ( although I am not sure why did you ask) You may
Instantiate the class
Make it static
Keep the class object in a application variable / Cache / View State etc
Use extension method which will give you random number ( You dont have to use another class in that case)
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