I have one abstract class named A, and other classes (B, C, D, E, ...) that implements A. My derived classes are holding values of different types. I also have a list of A objects.
abstract class A { }
class B : class A
{
public int val {get;private set;}
}
class C : class A
{
public double val {get;private set;}
}
class D : class A
{
public string val {get;private set;}
}
class Program
{
static void Main(string[] args)
{
List list = new List { new B(), new C(), new D(), new E() };
// ...
foreach (A item in list)
{
Console.WriteLine(String.Format("Value is: {0}", item.val);
}
}
}
...where the .val is not known by the base-class ofc.
How can i get this dynamic behaviour? I don't want to use getType in a long switch/if-statements.
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.
Even though the derived class can't call it in the base class, the base class can call it which effectively calls down to the (appropriate) derived class. And that's what the Template Method pattern is all about.
The correct way is to add a method DoSomeMagic() in the base class, with default implementation, or abstract. The derived class should than override it to do its magic.
A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.
If you just want to get the string representation of val i recoment overriding ToString in each of the sub classes
public override string ToString()
{
return val.ToString();
}
either way if you want the data in a sub class you need to represent it in the base class as some type they all have in common (like object). and you could do it like this
abstract class A
{
public abstract object GetValue();
}
class B : class A
{
public int val {get;private set;}
public override object GetValue()
{
return val;
}
}
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