Defining the subtype of an object after it's created

wasmachien :

Let's say I have following classes:

public class Animal {
  public string name;
  public int age;
  public bool canBark;
}

public class Dog : Animal {
  }

And instantiate an Animal like this:

Animal a = new Animal();

Is there anyway of downconverting this instance to a Dog instance after it's created? Or am I forced to recognize that my Animal is a Dog when I create it? The reason I'm having this problem is because my instance is created by calling a factory class that returns a type based on a JSON file that I feed it. The canBark attribute value is calculated by looking at several seemingly unrelated fields in that file. It seems it make more sense to determine that something is a Dog by looking at the canBark field, rather than those JSON fields.

public class AnimalFactory{
  public static Animal Create(JObject json){
    Animal a = new Animal();
    a.canBark = (json["someField"]["someOtherField"].ToString() == "abc")
    .....
}

I kind of solve this problem right now by having a constructor in the Dog class that takes an Animal as its argument and simply assigns the values of that instance's variables to its own. But this is not a very flexible way as I would need to add a line in each subclass constructor everytime I add a field.

So, is the best way of determining the type by moving that decision to the instance creation or is there some other way?

Jon Skeet :

Is there anyway of downconverting this instance to a Dog instance after it's created?

No. The type of an object can never be changed after construction, in either Java or .NET. You'll need to change your factory code to create an instance of the right class. It's not immediately clear how the canBark part relates to the rest of the question, but fundamentally you need to have somewhere that decides what kind of object to create based on the JSON content - or change your design so it can use the same object type in all cases.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113446&siteId=1