I have made two objects, i don't know what is the difference between them also. Is anyone count as a good practice? examples are appreciated! also, mark the advantages of both. Is it that I making a very simple code that's why I'm not seeing the difference?
class Program
{
static void Main()
{
MYway addison = new Addison(4, 6); //OBJ 1
Addison addison2 = new Addison(4, 6); // OBJ 2
Console.ReadKey();
}
}
abstract class MYway
{
abstract protected object Calculate(object value1, object value2);
}
class Addison: MYway
{
public Addison(double v1,double v2)
{
Console.WriteLine(Calculate(v1,v2));
}
protected override object Calculate(object value1, object value2)
{
return (double)value1 + (double)value2;
}
}
Output:
10
10
Starting from class definition. In my experience it is better to start with concrete implementation and then later (only if needed) extract some abstraction. I'm not sure whose words are these but: "Abstraction should be discovered". So you shouldn't start your design from abstract keyword (in your example I would delete abstract class)
Another thing is that classes should encapsulate state and behavior and in your example you don't have a state (numbers you are passing into constructor are not store anywhere). It means that you would be fine only with static method that calculate
public static class Addison
{
public static object Calculate(object value1, object value2)
{
return (double)value1 + (double)value2;
}
}
and you can use it:
class Program
{
static void Main()
{
object addison = Addison.Calculate(4, 6); //OBJ 1
object addison2 = Addison.Calculate(4, 6); // OBJ 2
Console.ReadKey();
}
}
If you would like to actually encapsulate state and behavior then
public class Addison
{
private object _value1;
private object _value2;
public Addision(object value1, object value2)
{
_value1 = value1;
_value2 = value2;
}
public object Calculate()
{
return (double)_value1 + (double)_value2;
}
}
class Program
{
static void Main()
{
Addison addison = new Addison(4, 6); //OBJ 1
Addison addison2 = new Addison(4, 6); // OBJ 2
Console.WriteLine(addison.Calculate());
Console.WriteLine(addison2.Calculate());
Console.ReadKey();
}
}
In above example you values 4 and 6 are stored in private (not accessible from outside) fields. And Calculate method use them to produce result.
Now if you ask what is a difference between addison
and addison2
:
- this are two different instances of the same class
- they occupy two different places in memory (their references are not equal)